package com.zmn.oms.zmn.business.impl.work;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.zmn.aws.common.model.community.CommunityBaseInfoDRO;
import com.zmn.aws.dubbo.interfaces.community.CommunityUserOrderRelationListRemoteService;
import com.zmn.base.channel.common.dro.ChannelDRO;
import com.zmn.base.channel.dubbo.interfaces.channel.ChannelListRemoteService;
import com.zmn.base.common.data.common.dro.company.CompanyContactDRO;
import com.zmn.base.common.data.dubbo.interfaces.company.CompanyListRemoteService;
import com.zmn.base.engineer.common.dro.foreign.engineer.ForeignEngineerCooperateInfoDRO;
import com.zmn.base.invoice.common.dro.InvoiceInfoDRO;
import com.zmn.base.invoice.common.enums.InvoiceStatusEnum;
import com.zmn.base.invoice.common.enums.InvoiceTypeEnum;
import com.zmn.base.invoice.dubbo.interfaces.manage.InvoiceInfoListRemoteService;
import com.zmn.base.engineer.common.dro.foreign.engineer.ForeignEngineerDetailInfoDRO;
import com.zmn.base.engineer.common.dro.foreign.engineer.ForeignEngineerOnlineStatusDRO;
import com.zmn.base.engineer.common.enums.EngineerRoleEnum;
import com.zmn.base.engineer.common.pagination.IPageInfo;
import com.zmn.base.engineer.common.query.foreign.engineer.ForeignEngineerQuery;
import com.zmn.base.engineer.dubbo.interfaces.engineer.cooperate.EngineerCooperateInfoListRemoteService;
import com.zmn.base.engineer.dubbo.interfaces.foreign.EngineerListRemoteService;
import com.zmn.base.engineer.dubbo.interfaces.foreign.EngineerOnlineRemoteService;
import com.zmn.base.invoice.common.dro.InvoiceInfoDRO;
import com.zmn.base.invoice.common.enums.InvoiceStatusEnum;
import com.zmn.base.invoice.dubbo.interfaces.manage.InvoiceInfoListRemoteService;
import com.zmn.base.oms.common.model.es.orderwork.*;
import com.zmn.base.plat.engine.common.constant.DubboConsts;
import com.zmn.base.price.common.dto.item.ItemDRO;
import com.zmn.base.price.common.dto.item.ItemPriceQuery;
import com.zmn.base.price.common.dto.meter2.MeterItemPriceQuery;
import com.zmn.base.price.dubbo.interfaces.calculate.ItemPriceRemoteService;
import com.zmn.base.price.dubbo.interfaces.calculate.MeterFlow2RemoteService;
import com.zmn.base.product.common.consts.BaseProductConsts;
import com.zmn.base.product.dubbo.interfaces.product.foreign.ProductBusinessLineForeignListRemoteService;
import com.zmn.biz.abnormal.common.dro.AbnorAbnormalOrderDRO;
import com.zmn.biz.abnormal.common.dro.AbnormalCategDRO;
import com.zmn.biz.abnormal.dubbo.interfaces.AbnormalListRemoteService;
import com.zmn.biz.complain.common.dro.complain.ChsComplainLevelDRO;
import com.zmn.biz.complain.common.dro.complain.ChsComplainSimpleDRO;
import com.zmn.biz.complain.dubbo.interfaces.complain.ChsComplainApiListRemoteService;
import com.zmn.biz.loan.common.dro.PartLoanDRO;
import com.zmn.biz.loan.common.enums.DebtStatusEnum;
import com.zmn.biz.loan.common.enums.PayTypeEnum;
import com.zmn.biz.loan.dubbo.interfaces.LoanListRemoteService;
import com.zmn.brs.common.enums.EventEnum;
import com.zmn.brs.common.enums.RecordFieldEnum;
import com.zmn.brs.starter.annotation.RecordField;
import com.zmn.brs.starter.annotation.StaffOperateRecord;
import com.zmn.cms.common.dto.source.PlayVideoRecordDRO;
import com.zmn.cms.common.enums.ServiceIdTypeEnum;
import com.zmn.cms.common.enums.VideoPlayTypeEnum;
import com.zmn.cms.dubbo.interfaces.source.SourceVideoRecordListRemoteService;
import com.zmn.common.dictionary.GlobalDict;
import com.zmn.common.dto2.Option;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.encode.EncodeUtil;
import com.zmn.common.utils.math.MoneyUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.consts.GateTypeConsts;
import com.zmn.consts.GlobalConsts;
import com.zmn.dms.common.constant.MasterBonusRecordConstants;
import com.zmn.dms.common.enums.DiscountTypeEnums;
import com.zmn.dms.dubbo.dto.masterbonus.MasterOrderBonusDRO;
import com.zmn.erp.common.newbiz.dro.oms.EngineerSpAccountResultDRO;
import com.zmn.erp.dubbo.interfaces.newbiz.account.AccountDetailListRemoteService;
import com.zmn.manager.mq.interfaces.ZmnMQSender;
import com.zmn.mcc.cas.web.StaffAdminService;
import com.zmn.mcc.common.dto.role.RoleDRO;
import com.zmn.mcc.common.dto.staff.StaffDRO;
import com.zmn.mcc.dubbo.interfaces.role.RoleListRemoteService;
import com.zmn.mcc.dubbo.interfaces.staff.StaffListRemoteService;
import com.zmn.oms.business.interfaces.conf.channel.ConfOrderChannelBService;
import com.zmn.oms.business.interfaces.es.OrderWorkEsBService;
import com.zmn.oms.business.interfaces.log.OrderLogBService;
import com.zmn.oms.business.interfaces.log.OrderRedistributeLogBService;
import com.zmn.oms.business.interfaces.master.OrderMasterBService;
import com.zmn.oms.business.interfaces.order.OrderBService;
import com.zmn.oms.business.interfaces.servtype.ServItemBService;
import com.zmn.oms.business.interfaces.tmall.OrderTmallExtendBService;
import com.zmn.oms.business.interfaces.work.OrderWorkERPQueryBService;
import com.zmn.oms.business.interfaces.work.OrderWorkListBService;
import com.zmn.oms.business.interfaces.work.OrderWorkPositionBService;
import com.zmn.oms.business.interfaces.work.epidemiccontrol.OrderWorkEpidemicControlBService;
import com.zmn.oms.business.interfaces.work.masterwork.MasterWorkBService;
import com.zmn.oms.common.constant.*;
import com.zmn.oms.common.dro.conf.channel.ConfOrderChannelDRO;
import com.zmn.oms.common.dro.normal.order.OrderIncomeDetailDRO;
import com.zmn.oms.common.dto.MapDTO;
import com.zmn.oms.common.enums.EncryptFieldTypeEnum;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.common.utils.ChannelUtil;
import com.zmn.oms.common.utils.MathUtil;
import com.zmn.oms.common.utils.MobileUtil;
import com.zmn.oms.constant.MessageQueueTopicConstant;
import com.zmn.oms.manager.utils.OmsMqTagConsts;
import com.zmn.oms.model.bo.report.TimeoutStatusBO;
import com.zmn.oms.model.dto.order.OrderUserDetailDTO;
import com.zmn.oms.model.dto.work.modify.OrderServItemTypeDTO;
import com.zmn.oms.model.dto.work.refund.RefundDTO;
import com.zmn.oms.model.entity.changerecord.OrderChangeRecord;
import com.zmn.oms.model.entity.channelprepay.OrderChannelPrepay;
import com.zmn.oms.model.entity.comment.OrderComment;
import com.zmn.oms.model.entity.comment.OrderCommentDetail;
import com.zmn.oms.model.entity.conf.attachment.ConfOrderAttachmentCategory;
import com.zmn.oms.model.entity.conf.attachment.ConfOrderAttachmentCategoryQuery;
import com.zmn.oms.model.entity.conf.ordertag.ConfOrderTag;
import com.zmn.oms.model.entity.conf.ordertag.ConfOrderTagQuery;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.discount.OrderDiscount;
import com.zmn.oms.model.entity.discount.OrderPayDiscount;
import com.zmn.oms.model.entity.factory.OrderFactory;
import com.zmn.oms.model.entity.fcorderpart.OrderFactoryPart;
import com.zmn.oms.model.entity.fcorderpart.OrderFactoryPartPost;
import com.zmn.oms.model.entity.log.OrderChannelDockingLog;
import com.zmn.oms.model.entity.log.OrderLog;
import com.zmn.oms.model.entity.log.OrderRedistributeLog;
import com.zmn.oms.model.entity.master.OrderMaster;
import com.zmn.oms.model.entity.member.OrderMember;
import com.zmn.oms.model.entity.nonstandard.OrderNonstandard;
import com.zmn.oms.model.entity.order.OrderExtend;
import com.zmn.oms.model.entity.orderattachment.OrderAttachment;
import com.zmn.oms.model.entity.part.OrderPart;
import com.zmn.oms.model.entity.pay.OrderPay;
import com.zmn.oms.model.entity.post.OrderPost;
import com.zmn.oms.model.entity.product.OrderProduct;
import com.zmn.oms.model.entity.product.OrderProductExtend;
import com.zmn.oms.model.entity.remark.OrderRemark;
import com.zmn.oms.model.entity.review.OmsOrderReview;
import com.zmn.oms.model.entity.serviceitem.OrderServiceItem;
import com.zmn.oms.model.entity.serviceitem.OrderServiceItemCell;
import com.zmn.oms.model.entity.shop.OrderShop;
import com.zmn.oms.model.entity.statement.OrderStatement;
import com.zmn.oms.model.entity.tag.OrderTag;
import com.zmn.oms.model.entity.tamllextend.OrderTmallExtend;
import com.zmn.oms.model.entity.track.OrderTrack;
import com.zmn.oms.model.entity.visit.OrderVisit;
import com.zmn.oms.model.entity.warn.OrderWarn;
import com.zmn.oms.model.entity.warn.OrderWarnQuery;
import com.zmn.oms.model.entity.warn.OrderWarnReplyEvent;
import com.zmn.oms.model.entity.warranty.OrderWarranty;
import com.zmn.oms.model.entity.warranty.OrderWarrantyProduct;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.entity.work.OrderWorkQuery;
import com.zmn.oms.model.entity.work.OrderWorkRelation;
import com.zmn.oms.model.entity.xno.OrderXnoBind;
import com.zmn.oms.model.entity.xno.OrderXnoBindQuery;
import com.zmn.oms.model.vo.changerecord.ZsOrderChangeRecordVO;
import com.zmn.oms.model.vo.log.OrderChannelDockingLogVO;
import com.zmn.oms.model.vo.member.OrderMemberReviewVO;
import com.zmn.oms.model.vo.part.ZsOrderPartVO;
import com.zmn.oms.model.vo.warning.OrderTagVO;
import com.zmn.oms.model.vo.warning.TrackAbnormalWarningVO;
import com.zmn.oms.model.vo.warning.ZsWarningVO;
import com.zmn.oms.model.vo.work.OrderWorkPositionVO;
import com.zmn.oms.model.vo.work.ZsOrderWorkServiceItemExportVO;
import com.zmn.oms.model.vo.work.ZsOrderWorkVO;
import com.zmn.oms.model.vo.work.attachmen.OrderWorkAttachmentDetailVO;
import com.zmn.oms.model.vo.work.detail.*;
import com.zmn.oms.model.vo.work.modify.OrderPostVO;
import com.zmn.oms.services.interfaces.changerecord.OrderChangeRecordService;
import com.zmn.oms.services.interfaces.channelprepay.OrderChannelPrepayService;
import com.zmn.oms.services.interfaces.comment.OrderCommentService;
import com.zmn.oms.services.interfaces.conf.attachment.ConfOrderAttachmentCategoryService;
import com.zmn.oms.services.interfaces.conf.ordertag.ConfOrderTagService;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.discount.OrderDiscountService;
import com.zmn.oms.services.interfaces.express.OrderPostService;
import com.zmn.oms.services.interfaces.factory.OrderFactoryService;
import com.zmn.oms.services.interfaces.fcorderpart.OrderFactoryPartPostService;
import com.zmn.oms.services.interfaces.fcorderpart.OrderFactoryPartService;
import com.zmn.oms.services.interfaces.invoice.OrderInvoiceService;
import com.zmn.oms.services.interfaces.master.OrderMasterService;
import com.zmn.oms.services.interfaces.member.OrderMemberService;
import com.zmn.oms.services.interfaces.nonstandard.OrderNonstandardService;
import com.zmn.oms.services.interfaces.order.OrderExtendService;
import com.zmn.oms.services.interfaces.order.OrderService;
import com.zmn.oms.services.interfaces.orderattachment.OrderAttachmentService;
import com.zmn.oms.services.interfaces.orderencrypt.OrderEncryptService;
import com.zmn.oms.services.interfaces.orderpaydiscount.OrderPayDiscountService;
import com.zmn.oms.services.interfaces.part.OrderPartService;
import com.zmn.oms.services.interfaces.pay.OrderPayService;
import com.zmn.oms.services.interfaces.product.OrderProductExtendService;
import com.zmn.oms.services.interfaces.product.OrderProductService;
import com.zmn.oms.services.interfaces.remark.OrderRemarkDetailService;
import com.zmn.oms.services.interfaces.remark.OrderRemarkService;
import com.zmn.oms.services.interfaces.review.OmsOrderReviewService;
import com.zmn.oms.services.interfaces.serviceitem.OrderServiceItemService;
import com.zmn.oms.services.interfaces.shop.OrderShopService;
import com.zmn.oms.services.interfaces.statement.OrderStatementService;
import com.zmn.oms.services.interfaces.tag.OrderTagService;
import com.zmn.oms.services.interfaces.track.OrderTrackService;
import com.zmn.oms.services.interfaces.visit.OrderVisitService;
import com.zmn.oms.services.interfaces.warn.OrderWarnReplyService;
import com.zmn.oms.services.interfaces.warn.OrderWarnService;
import com.zmn.oms.services.interfaces.warranty.OrderWarrantyProductService;
import com.zmn.oms.services.interfaces.warranty.OrderWarrantyService;
import com.zmn.oms.services.interfaces.work.OrderWorkRelationService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.services.interfaces.xno.OrderXnoService;
import com.zmn.oms.third.zhimi.ZhimiConsts;
import com.zmn.oms.third.zhimi.entity.ZhimiOrderExtend;
import com.zmn.oms.third.zhimi.service.ZhimiOrderExtendService;
import com.zmn.oms.zmn.business.interfaces.log.OrderChannelDockingLogBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkQueryBService;
import com.zmn.oms.zmn.business.interfaces.work.customwork.ZsDistributeWorkBService;
import com.zmn.pay.common.constant.PayConsts;
import com.zmn.performance.common.dro.order.OrderBehaviorDRO;
import com.zmn.performance.common.dro.order.OrderTimeOutWarningCheckDRO;
import com.zmn.performance.dubbo.interfaces.order.OrderBehaviorListRemoteService;
import com.zmn.performance.dubbo.interfaces.order.OrderTimeoutWarningListRemoteService;
import com.zmn.sp.common.model.manage.SpServProviderDRO;
import com.zmn.sp.dubbo.interfaces.manage.SpManageListRemoteService;
import com.zmn.track.common.constant.TrackConsts;
import com.zmn.track.dubbo.dto.TrackWorkDRO;
import com.zmn.track.dubbo.dto.TrackWorkQuery;
import com.zmn.track.dubbo.interfaces.trackwork.TrackWorkListRemoteService;
import com.zmn.uuc.common.dro.user.UserDetailDRO;
import com.zmn.uuc.dubbo.interfaces.user.UserListRemoteService;
import com.zmn.vas.common.dro.member.MemberDRO;
import com.zmn.vas.common.dro.order.ExtendedWarrantyDRO;
import com.zmn.vas.common.dro.order.card.times.OrderTimesCardDRO;
import com.zmn.vas.dubbo.consts.VasDubboConsts;
import com.zmn.vas.dubbo.interfaces.member.MemberListRemoteService;
import com.zmn.vas.dubbo.interfaces.order.VasOrderListRemoteService;
import com.zmn.vas.dubbo.interfaces.order.card.times.VasOrderTimesCardListRemoteService;
import com.zmn.xno.dubbo.interfaces.XnoRemoteService;
import lombok.SneakyThrows;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.filter.ParsedFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 类描述：啄木鸟订单查询
 * @author lujia
 * @date 2018/12/06 22:47
 */
@Service
public class ZsOrderWorkQueryBServiceImpl implements ZsOrderWorkQueryBService {

    private final static Logger logger = LoggerFactory.getLogger(ZsOrderWorkQueryBServiceImpl.class);

    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    protected ChannelListRemoteService channelListRemoteService;
    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    protected ProductBusinessLineForeignListRemoteService productBusinessLineListRemoteService;
    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    protected CompanyListRemoteService companyListRemoteService;
//    @Reference(version = com.zmn.mer.dubbo.utils.DubboConsts.INTERFACE_VERSION, check = false)
//    protected FactoryListRemoteService factoryListRemoteService;
    @Reference(version = com.zmn.mcc.dubbo.dto.DubboConsts.INTERFACE_VERSION, check = false)
    private RoleListRemoteService roleListRemoteService;
    @Reference(version = com.zmn.uuc.common.constant.DubboConsts.INTERFACE_VERSION, check = false)
    private UserListRemoteService userListRemoteService;
    @Reference(version = com.zmn.vas.dubbo.consts.VasDubboConsts.INTERFACE_VERSION, check = false)
    private MemberListRemoteService memberListRemoteService;
    @Reference(version = com.zmn.erp.dubbo.utils.DubboConsts.INTERFACE_VERSION, check = false)
    AccountDetailListRemoteService accountDetailListRemoteService;
    @Reference(version = com.zmn.base.engineer.common.constants.DubboConsts.INTERFACE_VERSION, check = false)
    EngineerListRemoteService engineerListRemoteService;
    @Reference(check = false, version = com.zmn.performance.dubbo.consts.DubboConsts.INTERFACE_VERSION)
    OrderTimeoutWarningListRemoteService orderTimeoutWarningListService;
    //@Reference(version = com.zmn.base.engineer.common.constants.DubboConsts.INTERFACE_VERSION, check = false)
    //private EngineerTouchListRemoteService engineerTouchListRemoteService;
    @Reference(version = com.zmn.base.engineer.common.constants.DubboConsts.INTERFACE_VERSION, check = false)
    private   EngineerOnlineRemoteService engineerOnlineRemoteService;
    @Reference(version = VasDubboConsts.INTERFACE_VERSION, check = false)
    private VasOrderListRemoteService vasOrderListRemoteService;
   // @Reference(version = com.zmn.base.engineer.common.constants.DubboConsts.INTERFACE_VERSION, check = false)
    //private EngineerProductGroupListRemoteService engineerProductGroupListRemoteService;

    @Reference(version = com.zmn.base.engineer.common.constants.DubboConsts.INTERFACE_VERSION, check = false)
    private EngineerCooperateInfoListRemoteService engineerCooperateInfoListRemoteService;

    @Reference(version = com.zmn.erp.dubbo.utils.DubboConsts.INTERFACE_VERSION, check = false)
    private InvoiceInfoListRemoteService invoiceInfoListRemoteService;
    @Reference(version = com.zmn.biz.complain.common.constant.DubboConsts.INTERFACE_VERSION, check = false)
    private ChsComplainApiListRemoteService chsComplainApiListRemoteService;
    @Reference(version = com.zmn.biz.abnormal.common.constant.DubboConsts.INTERFACE_VERSION, check = false, timeout = 2000)
    private AbnormalListRemoteService abnormalListRemoteService;
    @Reference(version = DubboConsts.INTERFACE_VERSION, check = false)
    private StaffListRemoteService staffListRemoteService;
    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    private MeterFlow2RemoteService meterFlow2RemoteService;
    @Resource
    private ConfOrderChannelBService confOrderChannelBService;
    @Reference(version = com.zmn.track.dubbo.consts.DubboConsts.INTERFACE_VERSION, check = false)
    private TrackWorkListRemoteService trackWorkListRemoteService;
    @Reference(version = com.zmn.sp.dubbo.utils.DubboConsts.INTERFACE_VERSION, check = false)
    private SpManageListRemoteService spManageListRemoteService;
    @Reference(version = com.zmn.performance.dubbo.consts.DubboConsts.INTERFACE_VERSION, check = false)
    private OrderBehaviorListRemoteService orderBehaviorListRemoteService;
    @Reference(version = com.zmn.cms.dubbo.constant.DubboConsts.INTERFACE_VERSION, check = false)
    private SourceVideoRecordListRemoteService sourceVideoRecordListRemoteService;
    @Reference(version = com.zmn.aws.dubbo.utils.DubboConstants.INTERFACE_VERSION, check = false)
    private CommunityUserOrderRelationListRemoteService communityUserOrderRelationListRemoteService;
    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    private ItemPriceRemoteService itemPriceRemoteService;
    @Reference(version = com.zmn.xno.common.constant.SystemConstants.DUBBO_CONSTS_INTERFACE_VERSION, check = false)
    private XnoRemoteService xnoRemoteService;
    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION, check = false)
    private LoanListRemoteService loanListRemoteService;
    @Reference(version = com.zmn.vas.dubbo.consts.VasDubboConsts.INTERFACE_VERSION, check = false)
    private VasOrderTimesCardListRemoteService vasOrderTimesCardListRemoteService;


    @Autowired
    OrderWorkListBService orderWorkListBService;
    @Autowired
    OrderService orderService;
    @Autowired
    OrderWorkService orderWorkService;
    @Autowired
    OrderDetailService orderDetailService;
    @Autowired
    OrderExtendService orderExtendService;
    @Autowired
    OrderProductService orderProductService;
    @Autowired
    OrderProductExtendService orderProductExtendService;
    @Autowired
    OrderServiceItemService orderServiceItemService;
    @Autowired
    OrderMasterService orderMasterService;
    @Autowired
    OrderMasterBService orderMasterBService;
    @Autowired
    OrderAttachmentService orderAttachmentService;
    @Autowired
    OrderDiscountService orderDiscountService;
    @Autowired
    OrderPartService orderPartService;
    @Autowired
    OrderTrackService orderTrackService;
    @Autowired
    OrderVisitService orderVisitService;
    @Autowired
    OrderNonstandardService orderNonstandardService;
    @Autowired
    OrderWarrantyService orderWarrantyService;
    @Autowired
    OrderWarrantyProductService orderWarrantyProductService;
    @Autowired
    OrderLogBService orderLogBService;
    @Autowired
    OrderRedistributeLogBService orderRedistributeLogBService;
    @Autowired
    OrderChannelDockingLogBService orderChannelDockingLogBService;
    @Autowired
    OrderCommentService orderCommentService;
    @Autowired
    OrderInvoiceService orderInvoiceService;
    @Autowired
    OrderMemberService orderMemberService;
    @Autowired
    OrderFactoryService orderFactoryService;
    @Autowired
    OrderFactoryPartService orderFactoryPartService;
    @Autowired
    OrderFactoryPartPostService orderFactoryPartPostService;
    @Autowired
    OrderWarnReplyService orderWarnReplyService;
    @Autowired
    OrderShopService orderShopService;
    @Autowired
    MasterWorkBService masterWorkBService;
    @Autowired
    OrderWarnService orderWarnService;
    @Autowired
    OrderTmallExtendBService orderTmallExtendBService;
    @Autowired
    OrderChangeRecordService orderChangeRecordService;
    @Autowired
    ZsDistributeWorkBService zsDistributeWorkBService;
    @Autowired
    OrderRemarkService orderRemarkService;
    @Autowired
    OrderRemarkDetailService orderRemarkDetailService;
    @Autowired
    OrderWorkPositionBService orderWorkPositionBService;
    @Autowired
    OrderPostService orderPostService;
    @Autowired
    OrderBService orderBService;
    @Autowired
    OrderWorkERPQueryBService orderWorkERPQueryBService;
    @Autowired
    ZhimiOrderExtendService zhimiOrderExtendService;
    @Autowired
    OrderStatementService orderStatementService;
    @Autowired
    OrderTagService orderTagService;
    @Autowired
    OrderPayService orderPayService;
    @Autowired
    ConfOrderTagService confOrderTagService;
    @Autowired
    OrderEncryptService orderEncryptService;
    @Autowired
    OmsOrderReviewService orderReviewService;
    @Autowired
    ServItemBService servItemBService;
    @Autowired
    OrderXnoService orderXnoService;
    @Autowired
    OrderWorkRelationService workRelationService;
    @Autowired
    OrderChannelPrepayService orderChannelPrepayService;
    @Autowired
    protected ConfOrderAttachmentCategoryService confOrderAttachmentCategoryService;

    @Autowired
    private OrderWorkEsBService orderWorkEsBService;

    @Autowired
    private OrderPayDiscountService orderPayDiscountService;

    @Autowired
    private OrderWorkEpidemicControlBService workEpidemicControlBService;

    @Resource
    private ZmnMQSender zmnMQSender;

    @Override
    public ZsOrderWorkDetailVO findOrderWorkDetail(Long orderId, Long workId) {

        // 运营后台工单详情
        ZsOrderWorkDetailVO detailVO = new ZsOrderWorkDetailVO();
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);
        OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(orderId);
        OrderExtend orderExtend = null;

        // 查看订单详情时，触发预警回复事件，回复渠道该订单的预警已知晓
        if (ChannelUtil.needOrderWarnReply(orderWork.getChannelId())) {
            OrderWarnReplyEvent orderWarnReplyEvent = new OrderWarnReplyEvent();
            orderWarnReplyEvent.setChannelId(orderWork.getChannelId());
            orderWarnReplyEvent.setOrderId(orderWork.getOrderId());
            orderWarnReplyEvent.setWorkId(orderWork.getWorkId());
            orderWarnReplyEvent.setOuterId(orderWork.getOuterId());

            orderWarnReplyService.orderWarnReplySync(orderWarnReplyEvent);
        }

        // 退款单
        boolean isRefundOrCompensateOrder = Objects.equals(OrderConsts.ORDER_TYPE_REFUND, orderWork.getType()) ||
                Objects.equals(OrderConsts.ORDER_TYPE_COMPENSATE, orderWork.getType());
        if (!isRefundOrCompensateOrder) {
            orderExtend = orderExtendService.findOrderExtendByOrderId(orderId);
        }

        // order work
        // 查询工单基础数据
        BeanMapper.copy(orderWork, detailVO);
        detailVO.setPlatName(GlobalConsts.getPlatName(orderWork.getPlat()));
        detailVO.setPlatWorkName(GlobalConsts.getPlatName(orderWork.getPlatWork()));
        detailVO.setCode(orderWork.getWorkId());
        detailVO.setOrderId(orderWork.getOrderId());
        detailVO.setCompanyId(orderWork.getCompanyId());
        detailVO.setManageCompanyId(orderWork.getManageCompanyId());
        detailVO.setManageCompanyName(orderWork.getManageCompanyName());
        detailVO.setMember(orderWork.getMember());
        detailVO.setBizType(Optional.ofNullable(detailVO.getBizType()).orElse(com.zmn.consts.GlobalConsts.BIZ_TYPE_C));
        detailVO.setBizTypeName(OrderConsts.getOrderBizType(detailVO.getBizType()));
        detailVO.setShardingNum(Math.abs(Long.hashCode(orderWork.getOrderId())) % 8);
        detailVO.setStatusName(OrderStatusConsts.getWorkStatusName(orderWork.getStatus()));
        detailVO.setResultStatusName(OrderStatusConsts.getWorkResultStatusName(orderWork.getResultStatus()));
        detailVO.setAppliqueStatusName(OrderConsts.getAppliqueStatusName(orderWork.getAppliqueStatus()));
        detailVO.setMasterImageStatusName(OrderConsts.getMasterImageStatusName(orderWork.getMasterImageStatus()));
        detailVO.setTypeName(OrderConsts.getOrderTypeName(orderWork.getType()));
        detailVO.setServCategName(orderDetail.getServCategName());
        detailVO.setPayStatusName(PayConsts.getPayStatusName(orderWork.getPayStatus()));
        detailVO.setChannelPrepayAmountPayStatusName(Objects.nonNull(orderWork.getChannelPrepayAmount()) ? PayConsts.getPayStatusName(orderWork.getChannelPrepayStatus()) : "");
        detailVO.setPrepayAmountPayStatusName(Objects.nonNull(orderWork.getPrepayAmount()) ? (Objects.equals(0, orderWork.getPrepayStatus()) ? "未支付" : PayConsts.getPayStatusName(orderWork.getPrepayStatus())) : "");
        detailVO.setDepositAmountPayStatusName(Objects.nonNull(orderWork.getDepositAmount()) ? PayConsts.getPayStatusName(orderWork.getDepositStatus()) : "");
        detailVO.setMasterAmountPayStatusName(Objects.nonNull(orderWork.getMasterAmount()) ? PayConsts.getPayStatusName(orderWork.getMasterPayStatus()) : "");
        detailVO.setRemark(orderDetail.getRemark());
        detailVO.setMember(orderWork.getMember());
        detailVO.setProvinceId(orderDetail.getProvinceId());
        detailVO.setSourceTypeName(OrderConsts.getSourceTypeName(orderWork.getSourceType()));
        // 小区信息
        try {
            CommunityBaseInfoDRO communityBaseInfoDRO = communityUserOrderRelationListRemoteService.getCommunityByWorkId(workId).getData();
            if (communityBaseInfoDRO != null) {
                detailVO.setCommunityId(communityBaseInfoDRO.getCommunityId());
                detailVO.setCommunityInfo(StringUtils.join(communityBaseInfoDRO.getCommunityName(), "/", communityBaseInfoDRO.getCommunityLevel()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 疫情管控级别设置
        try {
            if (Objects.equals(OrderStatusConsts.WORK_RESULT_DOING, orderWork.getResultStatus())) {
                Integer epidemicControlLevel = workEpidemicControlBService.getEpidemicControlLevel(orderDetail.getCountyId(),
                        orderDetail.getLongitude(), orderDetail.getLatitude());
                String epidemicControlMsg = null;
                switch (epidemicControlLevel) {
                    case 1:
                        epidemicControlMsg = "该地址2公里内有：疫情-防控区，请注意疫情防控。";
                        break;
                    case 2:
                        epidemicControlMsg = "该地址2公里内有：疫情-管控区，可联系客户是否继续服务。";
                        break;
                    case 3:
                        epidemicControlMsg = "该地址2公里内有：疫情-封控区，可联系客户是否继续服务。";
                        break;
                }
                detailVO.setEpidemicControlLevel(epidemicControlLevel);
                detailVO.setEpidemicControlMsg(epidemicControlMsg);
            }
        } catch (Exception ex) {
            logger.error("疫情管控级别设置 error", ex);
        }

        if (!Objects.isNull(orderWork.getSourceType())) {
            detailVO.setSourceType(String.valueOf(orderWork.getSourceType()));
        }
        Integer onlyVisit = orderWork.getOnlyVisit();
        if (onlyVisit == GlobalConsts.YES) {
            detailVO.setHomeAmount(detailVO.getMasterAmount());
            detailVO.setMasterAmount(null);
        }

        detailVO.setPartReimburseStatusName(
                isRefundOrCompensateOrder ? "" : OrderConsts.getOrderPartReimburseStatusName(orderWork.getPartReimburseStatus()));

        // 处理服务完成审核状态枚举值
        detailVO.setServiceCompleteReviewStatusName(OrderConsts.getReviewStatusName(orderWork.getServiceCompleteReviewStatus()));

        // 处理下单合同服务合同枚举值
        detailVO.setBizModeSourceName(OrderConsts.getBizModeName(orderWork.getBizModeSource()));
        detailVO.setBizModeName(OrderConsts.getBizModeName(orderWork.getBizMode()));
        detailVO.setBizLine(orderWork.getBizLine());
        this.processBizLineName(orderWork, detailVO);

        // 派单路径
        detailVO.setDistributeWay(orderWork.getDistributeWay());
        // 行政子公司
        detailVO.setGridCompanyName(orderDetail.getGridCompanyName());
        // 行政服务商
        detailVO.setGridManageCompanyId(orderDetail.getGridManageCompanyId());
        detailVO.setGridManageCompanyName(orderDetail.getGridManageCompanyName());

        // 联系信息
        ZsOrderWorkDetailContactVO contactVO = new ZsOrderWorkDetailContactVO();
        contactVO.setContactName(orderDetail.getContactName());
        contactVO.setUserName(orderDetail.getUserName());
        contactVO.setGenderName(GlobalDict.getGender(orderDetail.getGender()));
        List<String> telephoneList = Lists.newArrayList();
        String telephone = orderDetail.getTelephone();
        telephoneList.add(telephone);
        String telephone2 = orderDetail.getTelephone2();
        if (StringUtil.isNotBlank(telephone2)) {
            telephoneList.add(telephone2);
        }
        String telephone3 = orderDetail.getTelephone3();
        if (StringUtil.isNotBlank(telephone3)) {
            telephoneList.add(telephone3);
        }
        contactVO.setTelephoneList(telephoneList);
        // 小号信息，只显示绑定中
        if (Objects.equals(orderDetail.getBindStatus(), OrderConsts.BIND_STATUS_BIND)) {
            List<String> bindTelephoneList = Lists.newArrayListWithCapacity(3);
            List<Boolean> bindTelephoneShowStateList = Lists.newArrayListWithCapacity(3);
            String bindTelephone = orderDetail.getBindTelephone();
            if (StringUtil.isNotBlank(bindTelephone)) {
                bindTelephoneList.add(bindTelephone);
            }
            String bindTelephone2 = orderDetail.getBindTelephone2();
            if (StringUtil.isNotBlank(bindTelephone2)) {
                bindTelephoneList.add(bindTelephone2);
            }
            String bindTelephone3 = orderDetail.getBindTelephone3();
            if (StringUtil.isNotBlank(bindTelephone3)) {
                bindTelephoneList.add(bindTelephone3);
            }
            contactVO.setBindTelephoneList(bindTelephoneList);
            try {
                contactVO.setBindTelephoneShowStateList(bindTelephoneShowStateList);
                for (String bindTel : bindTelephoneList) {
                    ResponseDTO<Boolean> booleanResponseDTO = xnoRemoteService.queryExposeByXno(bindTel);
                    logger.info("查询{}小号暴露状态结果:{}",bindTel,booleanResponseDTO.getData());
                    bindTelephoneShowStateList.add(booleanResponseDTO.getData());
                }
            } catch (Exception e) {
                logger.error("查询小号暴露状态失败", e);
                e.printStackTrace();
            }
        }
        // 临时小号信息，只显示绑定中
        this.processTempXnoBind(orderWork, contactVO);
        String provinceName = orderDetail.getProvinceName();
        String cityName = orderDetail.getCityName();
        String countyName = orderDetail.getCountyName();
        String street = orderDetail.getStreet();
        String address = orderDetail.getAddress();
        contactVO.setProvinceName(provinceName);
        contactVO.setCityName(cityName);
        contactVO.setCountyName(countyName);
        contactVO.setStreet(street);
        contactVO.setAddress(address);
        contactVO.setFullAddress(provinceName + " " + cityName + " " + countyName + " " + street + " " + StringUtils
                .defaultString(address, ""));
        contactVO.setLatitude(orderDetail.getLatitude());
        contactVO.setLongitude(orderDetail.getLongitude());
        detailVO.setContactVO(contactVO);

        // 查询订单产品数据 && 产品的服务项
        List<OrderProduct> orderProductList = orderProductService.listOrderProductByOrderId(orderId);
        List<ZsOrderWorkDetailProductVO> productVOList = BeanMapper
                .mapList(orderProductList, ZsOrderWorkDetailProductVO.class);
        productVOList.forEach(item -> {
            List<String> fault = Lists.newArrayList();
            if (StringUtils.isNotBlank(item.getFault())) {
                List<MapDTO> faultList = JSON.parseArray(item.getFault(), MapDTO.class);
                fault.addAll(Optional.ofNullable(faultList).orElse(Lists.newArrayListWithCapacity(0)).stream()
                        .map(MapDTO::getMapName).collect(Collectors.toList()));
            }
            if (StringUtils.isNotBlank(item.getRemark())) {
                fault.add(item.getRemark());
            }
            item.setFaultInfo(StringUtils.join(fault, "；"));
        });
        detailVO.setProductList(productVOList);

        // 查询产品服务项
        if (!isRefundOrCompensateOrder) {

            List<OrderProductExtend> orderProductExtendList = orderProductExtendService.listByOrderId(orderId);
            Map<Long, OrderProductExtend> orderProductMap = orderProductExtendList.stream()
                    .collect(Collectors.toConcurrentMap(OrderProductExtend::getProExtId, orderProduct -> orderProduct));
            List<OrderServiceItem> orderServiceItemList = orderServiceItemService.listByOrderId(orderId);
            if (!orderServiceItemList.isEmpty()) {
                Map<Long, List<OrderServiceItem>> serviceItemMap = orderServiceItemList.stream()
                        .collect(Collectors.groupingBy(OrderServiceItem::getProExtId));

                List<ZsOrderWorkDetailProductVO> serviceItemVoList = Lists.newArrayList();
                serviceItemMap.forEach((key, value) -> {
                    OrderProductExtend orderProduct = orderProductMap.get(key);

                    // 计价器2.0报价可能导致有错误的服务项
                    if (Objects.isNull(orderProduct)) {
                        zmnMQSender.send(MessageQueueTopicConstant.ZMN_TOPIC_OMS,
                                OmsMqTagConsts.ORDER_SERVICE_ITEM_DEL_MQ_TAG,
                                String.valueOf(orderId), String.valueOf(key));
                        return;
                    }

                    ZsOrderWorkDetailProductVO zsOrderWorkDetailProductVO = new ZsOrderWorkDetailProductVO();
                    zsOrderWorkDetailProductVO.setProExtId(orderProduct.getProExtId());
                    zsOrderWorkDetailProductVO.setProductName(orderProduct.getProductName());
                    Integer totalAmount = 0;
                    List<ZsOrderWorkDetailServiceItemVO> serviceItemVOList = Lists.newArrayList();

                    for (OrderServiceItem serviceItem : value) {
                        ZsOrderWorkDetailServiceItemVO serviceItemVO = new ZsOrderWorkDetailServiceItemVO();
                        serviceItemVO.setServiceItemName(serviceItem.getServItemName());
                        serviceItemVO.setAmount(serviceItem.getTotalPrice());
                        serviceItemVO.setNumber(serviceItem.getNumber());

                        // 复制服务项明细相关的数据
                        if (CollectionUtil.isNotNullOrEmpty(serviceItem.getItemDetailList())) {
                            List<ZsOrderWorkDetailServiceItemDetailVO> serviceItemDetailVOList = new ArrayList<>(serviceItem.getItemDetailList().size());
                            for (OrderServiceItemCell cell : serviceItem.getItemDetailList()) {
                                ZsOrderWorkDetailServiceItemDetailVO vo = new ZsOrderWorkDetailServiceItemDetailVO();
                                vo.setItemCellName(cell.getItemCellName());
                                vo.setCellPrice(cell.getCellPrice());
                                serviceItemDetailVOList.add(vo);
                            }
                            serviceItemVO.setServiceItemDetailVOList(serviceItemDetailVOList);
                        }

                        Integer totalPrice = serviceItem.getTotalPrice();
                        serviceItemVOList.add(serviceItemVO);
                        totalAmount += totalPrice;
                    }
                    zsOrderWorkDetailProductVO.setServiceItemVOList(serviceItemVOList);
                    zsOrderWorkDetailProductVO.setServiceItemTotalAmount(totalAmount);
                    serviceItemVoList.add(zsOrderWorkDetailProductVO);
                });
                serviceItemVoList.sort(Comparator.comparing(ZsOrderWorkDetailProductVO::getProExtId));
                detailVO.setServiceItemList(serviceItemVoList);

                int internalSettlementPrice = orderServiceItemList.stream()
                        .filter(e -> e.getInternalTotalPrice() != null)
                        .mapToInt(OrderServiceItem::getInternalTotalPrice).sum();
                int externalSettlementPrice = orderServiceItemList.stream().
                        filter(e -> e.getExternalTotalPrice() != null)
                        .mapToInt(OrderServiceItem::getExternalTotalPrice).sum();
                detailVO.setInternalSettlementAmount(internalSettlementPrice);
                detailVO.setExternalSettlementAmount(externalSettlementPrice);
            }
        }

        // 有投诉 才查询
        Integer complaintStatus = orderWork.getComplaintStatus();
        if (!isRefundOrCompensateOrder && Objects.equals(complaintStatus, GlobalConsts.YES)) {
            try {
                ResponseDTO<List<ChsComplainSimpleDRO>> complainResponse = chsComplainApiListRemoteService
                        .listComplainSimpleByOrderId(orderId);
                if (complainResponse.isSuccess() && CollectionUtil.isNotNullOrEmpty(complainResponse.getData())) {
                    List<ChsComplainSimpleDRO> items = complainResponse.getData();
                    List<ZsOrderWorkDetailComplaintVO> complaintVOS = BeanMapper
                            .mapList(items, ZsOrderWorkDetailComplaintVO.class);
                    detailVO.setComplaintVOList(complaintVOS);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 有异常才查询
        Integer abnormalStatus = orderWork.getAbnormalStatus();
        if (!isRefundOrCompensateOrder && Objects.equals(abnormalStatus, GlobalConsts.YES)) {
            try {
                com.zmn.common.dto2.ResponseDTO<List<AbnormalCategDRO>> listResponseDTO = abnormalListRemoteService
                        .listAbnormalCategByOrderId(orderId);
                if (listResponseDTO.isSuccess() && !CollectionUtils.isEmpty(listResponseDTO.getData())) {
                    List<AbnormalCategDRO> data = listResponseDTO.getData();
                    List<ZsOrderWorkDetailAbnormalVO> abnormalVOList = BeanMapper
                            .mapList(data, ZsOrderWorkDetailAbnormalVO.class);
                    detailVO.setAbnormalVOList(abnormalVOList);
                }
            } catch (Exception ex) {
            }
        }

        // 工单附件照片
        List<OrderAttachment> orderAttachments = orderAttachmentService.listAttachmentByOrderId(orderId);
        if (CollectionUtil.isNotNullOrEmpty(orderAttachments)){
            List<ConfOrderAttachmentCategory> confOrderAttachmentCategories = confOrderAttachmentCategoryService.listByQuery(new ConfOrderAttachmentCategoryQuery());
            Map<Integer, ConfOrderAttachmentCategory> categoryMap = confOrderAttachmentCategories.stream().
                    collect(Collectors.toMap(item -> item.getCategId(), item -> item, (p, u) -> p));

            List<OrderWorkAttachmentDetailVO> appliqueImageAttachmentList = Lists.newArrayList();
            List<OrderWorkAttachmentDetailVO> imageAttachmentList = Lists.newArrayList();
            List<OrderWorkAttachmentDetailVO> videoAttachmentList = Lists.newArrayList();

            orderAttachments.forEach(e->{
                OrderWorkAttachmentDetailVO orderWorkAttachmentDetailVO = BeanMapper.map(e, OrderWorkAttachmentDetailVO.class);
                ConfOrderAttachmentCategory confOrderAttachmentCategory = categoryMap.get(e.getType());
                if (confOrderAttachmentCategory == null) {
                    return;
                }
                orderWorkAttachmentDetailVO.setTypeName(confOrderAttachmentCategory.getCategName());
                if (Objects.equals(e.getNeedReview(), com.zmn.consts.GlobalConsts.YES)) {
                    e.setReviewStatus(Optional.ofNullable(e.getReviewStatus()).orElse(OrderConsts.IMAGE_REVIEW_STATUS_WAITING));
                } else {
                    e.setReviewStatus(OrderConsts.IMAGE_REVIEW_STATUS_NO);
                }
                orderWorkAttachmentDetailVO.setReviewStatusName(OrderConsts.getImageReviewStatusName(e.getReviewStatus()));
                if (Objects.equals(confOrderAttachmentCategory.getType(), 2)) {
                    videoAttachmentList.add(orderWorkAttachmentDetailVO);
                } else {
                    if (e.getSrc().contains(",")) {
                        orderWorkAttachmentDetailVO.setSrcList(Arrays.asList(e.getSrc().split(",")).stream()
                                .map(String::toString).collect(Collectors.toList()));
                    }
                    if (OrderAttachmentTypeEnum.THZ.getCode().equals(e.getType())) {
                        // 贴花照，单独放
                        appliqueImageAttachmentList.add(orderWorkAttachmentDetailVO);
                    } else {
                        imageAttachmentList.add(orderWorkAttachmentDetailVO);
                    }
                }
            });

            detailVO.setAppliqueImageAttachmentList(appliqueImageAttachmentList);
            detailVO.setImageAttachmentList(imageAttachmentList.stream()
                    .sorted(Comparator.comparing(OrderWorkAttachmentDetailVO::getType)).collect(Collectors.toList()));
            detailVO.setVideoAttachmentList(videoAttachmentList.stream()
                    .sorted(Comparator.comparing(OrderWorkAttachmentDetailVO::getType)).collect(Collectors.toList()));
        }

        // 返修源工程师
        Long reworkId = orderWork.getReworkId();
        if (reworkId != null) {
            List<OrderMaster> masterList = orderMasterService.listMasterByWorkId(reworkId, reworkId, OrderConsts.ORDER_MASTER_TYPE_MAIN);
            if (!CollectionUtils.isEmpty(masterList)) {
                ZsOrderWorkDetailMasterVO reworkOriginalMaster = new ZsOrderWorkDetailMasterVO();
                reworkOriginalMaster.setMasterName(masterList.get(0).getMasterName());
                reworkOriginalMaster.setMasterPhone(masterList.get(0).getMasterPhone());
                reworkOriginalMaster.setStarLevel(masterList.get(0).getStarLevel());
                // 设置工程师产品分组
                /*if (Objects.nonNull(masterList.get(0).getMasterId())) {
                   try {
                       logger.debug("findOrderWorkDetail#getProductGroupByEngineerIdAndBizType 入参 [{}] [{}] [{}]",masterList.get(0).getMasterId(),orderWork.getBizType(),orderWork.getWorkId());
                       ResponseDTO<Option<Integer>> responseDTO = engineerCooperateInfoListRemoteService.getProductGroupByEngineerIdAndBizType(masterList.get(0).getMasterId(), orderWork.getBizType());
                       logger.debug("findOrderWorkDetail#getProductGroupByEngineerIdAndBizType 出参 [{}]",JSON.toJSONString(responseDTO));
                       if (responseDTO.isSuccess() && Objects.nonNull(responseDTO.getData())){
                           reworkOriginalMaster.setMasterGroupName(StringUtils.defaultString(responseDTO.getData().getLabel()));
                       }
                   } catch (Exception ex) {
                   }
                }*/

                Map<Integer, ForeignEngineerDetailInfoDRO> engineerBasicDetailInfoMap = this.getEngineerBasicDetailInfoMap(Sets.newHashSet(masterList.get(0).getMasterId()), orderWork.getBizType());
                if (CollectionUtil.isNotNullOrEmpty(engineerBasicDetailInfoMap) && Objects.nonNull(engineerBasicDetailInfoMap.get(masterList.get(0).getMasterId()))) {
                    ForeignEngineerDetailInfoDRO engineerDetailInfoDRO = engineerBasicDetailInfoMap.get(masterList.get(0).getMasterId());
                    // 设置产品组信息
                    if (CollectionUtil.isNotNullOrEmpty(engineerDetailInfoDRO.getCooperateInfoList())) {
                        reworkOriginalMaster.setMasterGroupName(StringUtils.defaultString(engineerDetailInfoDRO.getCooperateInfoList().get(0).getProductGroupName()));
                    }

                    // 设置工程师分层管理等级
                    reworkOriginalMaster.setHierarchyLevel(engineerDetailInfoDRO.getHierarchyLevel());
                }
                detailVO.setReworkOriginalMaster(reworkOriginalMaster);
            }
        }

        // 查询订单工程师列表
        List<OrderMaster> masterList = orderMasterService.listMasterByWorkId(orderId, workId);
        if (!CollectionUtils.isEmpty(masterList)) {

            // 查询工程师分组名称
            Set<Integer> masterIds = masterList.stream().map(OrderMaster::getMasterId).collect(Collectors.toSet());
            Map<Integer, ForeignEngineerOnlineStatusDRO> onlineStatusMap = listMasterOnlineStatusDROMap(orderWork, masterIds);
//            Map<Integer, String> identityMap = orderMasterBService.listMasterIdentityMap(masterIds);
            Map<Integer, ForeignEngineerDetailInfoDRO> engineerBasicDetailInfoMap = this.getEngineerBasicDetailInfoMap(masterIds, orderWork.getBizType());

            List<ZsOrderWorkDetailMasterVO> masterVOList = BeanMapper
                    .mapList(masterList, ZsOrderWorkDetailMasterVO.class);
            for (ZsOrderWorkDetailMasterVO item : masterVOList) {
                item.setTypeName(OrderConsts.getOrderMasterTypeName(item.getType()));
                /*try {
                    // 设置工程师产品分组
                    logger.debug("findOrderWorkDetail#getProductGroupByEngineerIdAndBizType 入参 [{}] [{}] [{}]",item.getMasterId(),orderWork.getBizType(),orderWork.getWorkId());
                    ResponseDTO<Option<Integer>> responseDTO = engineerCooperateInfoListRemoteService.getProductGroupByEngineerIdAndBizType(item.getMasterId(), orderWork.getBizType());
                    logger.debug("findOrderWorkDetail#getProductGroupByEngineerIdAndBizType 出参 [{}]",JSON.toJSONString(responseDTO));
                    if (responseDTO.isSuccess() && Objects.nonNull(responseDTO.getData())){
                        item.setMasterGroupName(StringUtils.defaultString(responseDTO.getData().getLabel()));
                    }
                } catch (Exception ex){
                }*/

                // 设置工程师在线状态
                if (Objects.nonNull(onlineStatusMap) && onlineStatusMap.containsKey(item.getMasterId())) {
                    ForeignEngineerOnlineStatusDRO mastMasterDRO = onlineStatusMap.get(item.getMasterId());
                    item.setAppOnline(mastMasterDRO.isAppOnline() ? GlobalConsts.YES : GlobalConsts.NO);
                }
//                if (Objects.nonNull(identityMap) && identityMap.containsKey(item.getMasterId())) {
//                    item.setIdentityName(Optional.ofNullable(identityMap.get(item.getMasterId())).orElse("工程师"));
//                }

                if (CollectionUtil.isNotNullOrEmpty(engineerBasicDetailInfoMap) && Objects.nonNull(engineerBasicDetailInfoMap.get(item.getMasterId()))) {
                    // 设置工程师身份
                    ForeignEngineerDetailInfoDRO engineerDetailInfoDRO = engineerBasicDetailInfoMap.get(item.getMasterId());
                    item.setIdentityName(Objects.equals(engineerDetailInfoDRO, EngineerRoleEnum.APPRENTICE.getCode()) ? "学徒" : "工程师");

                    // 设置产品组信息
                    if (CollectionUtil.isNotNullOrEmpty(engineerDetailInfoDRO.getCooperateInfoList())) {
                        item.setMasterGroupName(StringUtils.defaultString(engineerDetailInfoDRO.getCooperateInfoList().get(0).getProductGroupName()));
                    }

                    // 设置工程师分层管理等级
                    item.setHierarchyLevel(engineerDetailInfoDRO.getHierarchyLevel());
                }
            }
            detailVO.setMasterVOList(masterVOList);
        }

        //待自动派单
        boolean isAutoDistribute = zsDistributeWorkBService.isWaitAutoDistribute(orderWork);
        logger.debug("待自动派单 isAutoDistribute[{}]", isAutoDistribute);
        detailVO.setIsWaitAutoDistribute(isAutoDistribute);

        // 优惠列表
        if (!isRefundOrCompensateOrder) {
            List<OrderDiscount> discountList = orderDiscountService.listByOrderId(orderId);
            if (!CollectionUtils.isEmpty(discountList)) {
                List<ZsOrderWorkDetailDiscountVO> discountVOList = Lists.newArrayList();
                for (OrderDiscount orderDiscount : discountList) {
                    ZsOrderWorkDetailDiscountVO discountVO = new ZsOrderWorkDetailDiscountVO();
                    discountVO.setCategName(StringUtils.defaultString(DiscountTypeEnums.getSubName(orderDiscount.getCateg())));
                    discountVO.setTypeName(OrderConsts.getDiscountTypeName(orderDiscount.getType()));
                    discountVO.setAmount(orderDiscount.getAmount());
                    discountVO.setSellAmount(Optional.ofNullable(orderDiscount.getSellAmount()).orElse(0));
                    discountVO.setCouponCode(orderDiscount.getItemCode());
                    discountVO.setType(orderDiscount.getType());
                    discountVO.setCateg(orderDiscount.getCateg());

                    // 规则ID
                    if (Objects.equals(orderDiscount.getCateg(), DiscountTypeEnums.DISCOUNT_RULE_COMMON.getSubType())
                            || Objects.equals(orderDiscount.getCateg(), DiscountTypeEnums.DISCOUNT_RULE_ARTIFICIAL.getSubType())
                            || Objects.equals(orderDiscount.getCateg(), DiscountTypeEnums.DISCOUNT_ACTIVITY_LATE_COMPENSATE.getSubType())
                            || Objects.equals(orderDiscount.getCateg(), DiscountTypeEnums.DISCOUNT_FREE.getSubType())) {
                        discountVO.setSourceId(orderDiscount.getItemId());
                    } else if (Objects.equals(orderDiscount.getCateg(), DiscountTypeEnums.DISCOUNT_COUP_COMMON.getSubType())
                            || Objects.equals(orderDiscount.getCateg(), DiscountTypeEnums.DISCOUNT_COUP_VOUCHER.getSubType())
                            || Objects.equals(orderDiscount.getCateg(), DiscountTypeEnums.DISCOUNT_CHANNEL.getSubType())
                            || Objects.equals(orderDiscount.getCateg(), DiscountTypeEnums.DISCOUNT_COUP_CASH.getSubType())){
                        discountVO.setSourceId(orderDiscount.getSourceId());
                    }

                    discountVOList.add(discountVO);
                }
                detailVO.setDiscountVOList(discountVOList);
            }
        }

        // 配件
        if (!isRefundOrCompensateOrder) {
            List<OrderPart> orderPartList = orderPartService.listByOrderId(orderId);
            if (!CollectionUtils.isEmpty(orderPartList)) {

                Map<Integer, List<OrderPart>> partTypeMap = orderPartList.stream()
                        .collect(Collectors.groupingBy(OrderPart::getPartType));

                // 内采配件
                List<OrderPart> inPartList = partTypeMap.get(OrderConsts.PART_TYPE_SOURCING_IN);
                if (!CollectionUtils.isEmpty(inPartList)) {
                    int inSourcingCostAmount = inPartList.stream().mapToInt(
                            (e) -> MathUtil.amountMultiplyNumber(Optional.ofNullable(e.getCostPrice())
                                    .orElse(GlobalConsts.NONE), e.getNumber())).sum();
                    int inSourcingPurchaseAmount = inPartList.stream().mapToInt(
                            (e) -> MathUtil.amountMultiplyNumber(Optional.ofNullable(e.getPurchasePrice())
                                    .orElse(GlobalConsts.NONE), e.getNumber())).sum();
                    detailVO.setInSourcingPartList(processOrderDetailPart(inPartList));
                    detailVO.setInSourcingCostAmount(inSourcingCostAmount);
                    detailVO.setInSourcingPurchaseAmount(inSourcingPurchaseAmount);
                }

                // 外报配件
                List<OrderPart> outPartList = partTypeMap.get(OrderConsts.PART_TYPE_SOURCING_OUT);
                if (!CollectionUtils.isEmpty(outPartList)) {
                    int outSourcingCostAmount = outPartList.stream().mapToInt(
                            (e) -> MathUtil.amountMultiplyNumber(Optional.ofNullable(e.getCostPrice())
                                    .orElse(GlobalConsts.NONE), e.getNumber())).sum();
                    int outSourcingPurchaseAmount = outPartList.stream().mapToInt(
                            (e) -> MathUtil.amountMultiplyNumber(Optional.ofNullable(e.getPurchasePrice())
                                    .orElse(GlobalConsts.NONE), e.getNumber())).sum();
                    detailVO.setOutSourcingPartList(processOrderDetailPart(outPartList));
                    detailVO.setOutSourcingCostAmount(outSourcingCostAmount);
                    detailVO.setOutSourcingPurchaseAmount(outSourcingPurchaseAmount);
                }

                // 订单杂项费用
                List<OrderPart> deliverList = partTypeMap.get(OrderConsts.PART_TYPE_DELIVER);
                if (!CollectionUtils.isEmpty(deliverList)) {
                    int deliverAmount = deliverList.stream().mapToInt(
                            (e) -> MathUtil.amountMultiplyNumber(Optional.ofNullable(e.getPrice())
                                    .orElse(GlobalConsts.NONE), e.getNumber())).sum();
                    detailVO.setDeliverList(processOrderDetailPart(deliverList));
                    detailVO.setDeliverAmount(deliverAmount);
                }
            }
        }

        // 保内订单 已上门状态 未完成 进行中
        if (!isRefundOrCompensateOrder && Objects.equals(orderWork.getBizType(), com.zmn.consts.GlobalConsts.BIZ_TYPE_F) && Objects
                .equals(orderWork.getResultStatus(), OrderStatusConsts.WORK_RESULT_DOING)) {

            // 厂商配件
            List<OrderFactoryPart> orderFactoryPartList = orderFactoryPartService
                    .listOrderFactoryPartByOrderId(orderId);
            if (!CollectionUtils.isEmpty(orderFactoryPartList)) {

                // 加载所有厂商配件
                List<ZsOrderWorkFactoryPartVO> factoryParts = BeanMapper.mapList(orderFactoryPartList, ZsOrderWorkFactoryPartVO.class);

                // 过滤出已审核的配件
                orderFactoryPartList = orderFactoryPartList.stream()
                        .filter(e -> Objects.equals(e.getReviewStatus(), OrderConsts.REVIEW_STATUS_SUCCESS))
                        .collect(Collectors.toList());
                if (!orderFactoryPartList.isEmpty()) {

                    List<ZsOrderWorkFactoryPartVO> factoryPartList = BeanMapper.mapList(orderFactoryPartList, ZsOrderWorkFactoryPartVO.class);
                    detailVO.setFactoryPartList(factoryPartList);
                    detailVO.setFcPartList(factoryParts);

                    // 厂商配件邮寄信息
                    List<OrderFactoryPartPost> orderFactoryPartPostList = orderFactoryPartPostService.listOrderFactoryPartPostByOrderId(orderId);
                    if (!orderFactoryPartPostList.isEmpty()) {
                        Map<Integer, List<OrderFactoryPartPost>> factoryPartPostListMap = orderFactoryPartPostList
                                .stream().collect(Collectors.groupingBy(OrderFactoryPartPost::getFcOrderPartId));
                        factoryParts.forEach(e -> {
                            if (!factoryPartPostListMap.containsKey(e.getFcOrderPartId())) {
                                return;
                            }
                            List<OrderFactoryPartPost> orderFactoryPartPosts = factoryPartPostListMap.get(e.getFcOrderPartId());
                            List<ZsOrderWorkFactoryPartPostVO> factoryPartPostList = BeanMapper.mapList(orderFactoryPartPosts, ZsOrderWorkFactoryPartPostVO.class);
                            e.setFactoryPartPostList(factoryPartPostList);
                        });
                        factoryPartList.forEach(e -> {

                            if (!factoryPartPostListMap.containsKey(e.getFcOrderPartId())) {
                                return;
                            }
                            List<OrderFactoryPartPost> orderFactoryPartPosts = factoryPartPostListMap.get(e.getFcOrderPartId());
                            List<ZsOrderWorkFactoryPartPostVO> factoryPartPostList = BeanMapper.mapList(orderFactoryPartPosts, ZsOrderWorkFactoryPartPostVO.class);
                            factoryPartPostList.forEach(f -> {
                                f.setPostStatusName(GlobalConsts.getPostStatusName(f.getStatus()));
                                f.setPostTypeName(OrderConsts.getFactoryPartPostTypeName(f.getFcOrderPartPostType()));
                            });
                            e.setFactoryPartPostList(factoryPartPostList);
                        });
                    }
                }
            }
        }

        // 跟单列表（旧）
        List<OrderTrack> orderTrackList = orderTrackService.listOrderTrackByWorkId(orderId, workId);
        if (!CollectionUtils.isEmpty(orderTrackList)) {
            List<ZsOrderWorkDetailTrackVO> trackVOList = BeanMapper
                    .mapList(orderTrackList, ZsOrderWorkDetailTrackVO.class);
            detailVO.setTrackVOList(trackVOList);
        }

        // 是否有新跟单数据 & 是否有进行中的跟单
        isExistTrack(orderId, workId, detailVO);

        // 上门列表
        List<OrderVisit> orderVisitList = orderVisitService.listByOrderId(orderId);
        if (CollectionUtil.isNotNullOrEmpty(orderVisitList)) {

            Map<Long, OrderAttachment> map = new HashMap<>();
            if (CollectionUtil.isNotNullOrEmpty(orderAttachments)) {
                map = orderAttachments.stream().collect(Collectors.toMap(OrderAttachment::getAttachmentId, orderAttachment -> orderAttachment));
            }

            List<ZsOrderWorkDetailVisitVO> orderWorkDetailVisitList = BeanMapper.mapList(orderVisitList, ZsOrderWorkDetailVisitVO.class);
            Map<Long, OrderAttachment> finalMap = map;
            orderWorkDetailVisitList.forEach(item -> {
                item.setVisitTypeName(OrderVisitStatusConsts.getVisitTypeName(item.getVisitType()));
                item.setVisitStatusName(OrderVisitStatusConsts.getVisitStatusName(item.getVisitStatus()));
                // 处理照片附件
                if (StringUtil.isNotBlank(item.getAttachmentIds())) {
                    String[] ids = item.getAttachmentIds().split(",");
                    StringBuilder sb = new StringBuilder();
                    for (String s : ids) {
                        OrderAttachment attachment = finalMap.get(Long.valueOf(s));
                        if (Objects.nonNull(attachment)) {
                            sb.append(String.format("{{[img:%s]}}", attachment.getSrc()));
                        }
                    }
                    item.setImgSrc(sb.toString());
                }
            });
            detailVO.setVisitVOList(orderWorkDetailVisitList);
        }

        // 非标信息
        List<OrderNonstandard> orderNonstandards = orderNonstandardService.listNonstandardByOrderId(orderId);
        if (!CollectionUtils.isEmpty(orderNonstandards)) {
            ZsOrderNonstandardVO zsOrderNonstandardVO = new ZsOrderNonstandardVO();
            List<OrderNonstandard> collect = orderNonstandards.stream().filter(e -> Objects.equals(e.getType(), 1)).collect(Collectors.toList());
            List<OrderNonstandard> imgList = orderNonstandards.stream().filter(e -> Objects.equals(e.getType(), 2)).collect(Collectors.toList());
            if(CollectionUtil.isNotNullOrEmpty(imgList)){
                String imageSrc = imgList.get(0).getImageSrc();
                String[] split = imageSrc.split(",");
                zsOrderNonstandardVO.setImgList(Arrays.asList(split));
            }
            zsOrderNonstandardVO.setOrderNonstandardList(collect);
            detailVO.setNonstandardVO(zsOrderNonstandardVO);
        }


        // 评价
        if (!isRefundOrCompensateOrder) {
            try {
                List<OrderComment> commentList = orderCommentService.findChannelCommentListByKey(orderId);
                if (CollectionUtil.isNotNullOrEmpty(commentList)) {
                    List<ZsOrderWorkDetailCommentVO> commentVOList = Lists.newArrayList();
                    commentList.forEach(comment->{
                        ZsOrderWorkDetailCommentVO commentVO =new ZsOrderWorkDetailCommentVO();
                        commentVO.setScore(comment.getScore());
                        commentVO.setType(comment.getType());
                        commentVO.setTypeName(OrderConsts.getCommentTypeName(comment.getType()));
                        commentVO.setStoreName(comment.getStoreName());

                        StringJoiner stringJoiner = new StringJoiner("；");
                        if (StringUtils.isNotBlank(comment.getContent())) {
                            stringJoiner.add(comment.getContent());
                        }
                        List<OrderCommentDetail> orderCommentDetailList = comment.getDetailList();
                        if (!CollectionUtils.isEmpty(orderCommentDetailList)) {
                            orderCommentDetailList.forEach(item->{
                                if (StringUtils.isNotBlank(item.getMapName())) {
                                    stringJoiner.add(item.getMapName());
                                }
                            });
                        }
                        commentVO.setContent(stringJoiner.toString());
                        commentVOList.add(commentVO);
                    });

                    // 用户评价
                    detailVO.setUserCommentVO(commentVOList.stream().filter(item->Objects.equals(item.getType(), 2)).findAny().orElse(null));
                    // 渠道评价
                    detailVO.setChannelCommentVO(commentVOList.stream().filter(item->Objects.equals(item.getType(), 4)).findAny().orElse(null));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 保修卡
        if (!isRefundOrCompensateOrder) {
            OrderWarranty orderWarranty = orderWarrantyService.findByOrderId(orderId);
            if (orderWarranty != null) {
                List<OrderWarrantyProduct> warrantyProductList = orderWarrantyProductService.listByOrderId(orderId);
                ZsOrderWorkDetailWarrantyVO orderWorkDetailWarrantyVO = new ZsOrderWorkDetailWarrantyVO();
                orderWorkDetailWarrantyVO.setCode(orderWarranty.getCode());
                orderWorkDetailWarrantyVO.setEffectiveTime(orderWarranty.getEffectiveTime());
                orderWorkDetailWarrantyVO.setGrant(!NumberUtil.isNullOrZero(orderWarranty.getUserId()));
                orderWorkDetailWarrantyVO.setTypeName(OrderConsts.getWarrantyTypeName(orderWarranty.getType()));
                orderWorkDetailWarrantyVO.setType(orderWarranty.getType());
                orderWorkDetailWarrantyVO.setGrantUserName(getGrantUserName(orderWork, orderWarranty));

                // 有效状态 类型是 保修
                if (Objects.equals(orderWarranty.getType(), OrderConsts.ORDER_WARRANTY_TYPE_CARD) && (
                        Objects.equals(orderWarranty.getStatus(), OrderConsts.ORDER_WARRANTY_STATUS_VALID) ||
                                Objects.equals(orderWarranty.getStatus(), OrderConsts.ORDER_WARRANTY_STATUS_INVALID))
                ) {
                    warrantyProductList.stream().forEach(warrantyProduct -> {
                        boolean inWarranty = warrantyProduct.getExpiredTime() != null && (DateUtil.getNow().compareTo(warrantyProduct.getExpiredTime()) != 1);
                        if (Objects.equals(orderWarranty.getStatus(), OrderConsts.ORDER_WARRANTY_STATUS_INVALID)) {
                            inWarranty = false;
                        }
                        // TODO 修正数据 by liuying 保修天数数据，最少1天
                        int period = (int) DateUtil.getTimespan(orderWarranty.getEffectiveTime(), warrantyProduct.getExpiredTime(), DateUtil.UNIT_DAY);
                        long second = DateUtil.getTimespan(orderWarranty.getEffectiveTime(), warrantyProduct.getExpiredTime(), DateUtil.UNIT_SECOND);
                        if(second > 0 && period == 0){
                            period = 1;
                        }
                        if (!Objects.equals(warrantyProduct.getDay(), period) && period >= 0) {
                            OrderWarrantyProduct updateOrderWarrantyProduct = new OrderWarrantyProduct();
                            updateOrderWarrantyProduct.setExpiredTime(warrantyProduct.getExpiredTime());
                            updateOrderWarrantyProduct.setDay(period);
                            updateOrderWarrantyProduct.setWarrId(warrantyProduct.getWarrId());
                            updateOrderWarrantyProduct.setProId(warrantyProduct.getProId());
                            orderWarrantyProductService.updateExpiredTime(updateOrderWarrantyProduct);

                            warrantyProduct.setDay(period);
                        }
                        logger.info("warrantyProduct-->{}--period={}", warrantyProduct, period);
                        warrantyProduct.setInWarranty(inWarranty);
                    });
                }
                orderWorkDetailWarrantyVO.setOrderWarrantyProductList(warrantyProductList);

                // 特权订单 并且师傅收款额为0  不显示
                boolean noShow = Objects.equals(GlobalConsts.YES, orderWork.getMember()) && NumberUtil.isNullOrZero(orderWork.getMasterAmount());
                if (!noShow) {
                    detailVO.setWarranty(orderWorkDetailWarrantyVO);
                }
            }
        }

        // 发票
        ResponseDTO<InvoiceInfoDRO> invoiceInfoDROResponseDTO;
        try {
            invoiceInfoDROResponseDTO = invoiceInfoListRemoteService.getInvoiceInfoByBillId(workId);
            if (invoiceInfoDROResponseDTO.isSuccess() && Objects.nonNull(invoiceInfoDROResponseDTO.getData())) {
                InvoiceInfoDRO invoiceInfoDRO = invoiceInfoDROResponseDTO.getData();
                ZsOrderWorkDetailInvoiceVO invoiceVO = BeanMapper.map(invoiceInfoDRO, ZsOrderWorkDetailInvoiceVO.class);
                invoiceVO.setDrawerTime(DateUtil.toString(invoiceInfoDRO.getInvoiceTime(), DateUtil.FORMAT_DEFAULT));
                invoiceVO.setInvoiceAmount(invoiceInfoDRO.getTotalPriceWithTax().intValue());
                invoiceVO.setStatusName(InvoiceStatusEnum.getStatus(invoiceInfoDRO.getInvoiceStatus()));
                invoiceVO.setApplyTime(DateUtil.toString(invoiceInfoDRO.getCreateTime(), DateUtil.FORMAT_DEFAULT));
                invoiceVO.setInvoiceTypeName(InvoiceTypeEnum.getByCode(invoiceInfoDRO.getInvoiceType()).getName());
                detailVO.setInvoiceVO(invoiceVO);
            }
        } catch (Exception e) {
            logger.error("发票信息获取失败", e);
        }

        // 预付配件费信息
        ResponseDTO<List<PartLoanDRO>> partLoanListDRO;
        try {
            partLoanListDRO = loanListRemoteService.listDebtRecordByOrderId(orderWork.getOrderId());
            List<PartLoanDRO> partLoanDROList = partLoanListDRO.getData();
            if (partLoanListDRO.isSuccess() && CollectionUtil.isNotNullOrEmpty(partLoanDROList)) {

                List<ZsOrderWorkDetailPartLoanVO> partLoanVOList = partLoanDROList.stream().map(partLoanDRO -> {
                    ZsOrderWorkDetailPartLoanVO partLoanVO = BeanMapper.map(partLoanDRO, ZsOrderWorkDetailPartLoanVO.class);
                    // 借款进度状态
                    partLoanVO.setDebtStatusName(DebtStatusEnum.getNameByCode(partLoanVO.getDebtStatus()));

                    // 支付方式
                    partLoanVO.setPayTypeName(PayTypeEnum.getNameByCode(partLoanDRO.getPayType()));

                    // 还款方式
                    partLoanVO.setRepaymentTypeName(PayTypeEnum.getNameByCode(partLoanDRO.getRepaymentType()));
                    return partLoanVO;
                }).collect(Collectors.toList());

                detailVO.setPartLoanVOList(partLoanVOList);
            }
        } catch (Exception e) {
            logger.error("借款信息获取失败", e);
        }

        // 会员订单
        if (Objects.equals(orderWork.getSourceType(), OrderConsts.ORDER_SOURCE_TYPE_MEMBER) && !isRefundOrCompensateOrder) {
            OrderMember orderMember = orderMemberService.findMemberByKey(orderId);
            if (orderMember != null) {
                detailVO.setVasOrderId(orderMember.getVasOrderId());
                String electrFragileCode = orderMember.getFragileCode();
                if (StringUtil.isNotBlank(electrFragileCode)) {
                    try {
                        ResponseDTO<ExtendedWarrantyDRO> extendedWarrantyInfoByRespDTO = vasOrderListRemoteService.getExtendedWarrantyInfoByCode(electrFragileCode, orderWork.getWorkId());
                        if (extendedWarrantyInfoByRespDTO.isSuccess() && extendedWarrantyInfoByRespDTO.getData() != null) {
                            OrderMemberReviewVO orderMemberReviewVO = BeanMapper.map(orderMember, OrderMemberReviewVO.class);
                            BeanMapper.copy(orderWork, OrderMemberReviewVO.class);

                            ExtendedWarrantyDRO extendedWarrantyDRO = extendedWarrantyInfoByRespDTO.getData();
                            orderMemberReviewVO.setUserDeviceImageSrc(extendedWarrantyDRO.getElectrSrc());
                            orderMemberReviewVO.setUserFragilePasteImageSrc(extendedWarrantyDRO.getElectrFragileSrc());
                            orderMemberReviewVO.setUserNameplateImageSrc(extendedWarrantyDRO.getElectrNameplateSrc());
                            logger.info("orderMemberReviewVO:{}",orderMemberReviewVO);
                            detailVO.setOrderMemberReviewVO(orderMemberReviewVO);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                ZsOrderWorkDetailMemberOrderVO detailMemberOrderVO = BeanMapper.map(orderMember, ZsOrderWorkDetailMemberOrderVO.class);
                detailMemberOrderVO.setReviewStatusName(OrderConsts.getMemberReviewStatusName(orderMember.getReviewStatus()));
                detailVO.setMemberOrderVO(detailMemberOrderVO);
            }
        }

        // 支付信息
        List<OrderPay> orderPays = orderPayService.listAllOrderPayByOrderIdAndWorkId(orderId, workId);
        List<OrderPay> payList = orderPays.stream().filter(e -> {
            Integer amountType = e.getAmountType();
            Integer tradeType = e.getTradeType();
            return Objects.equals(tradeType, PayConsts.PAY_TRADE_TYPE_INTIME) && (
                    Objects.equals(amountType, OrderPayConsts.ORDER_PAY_PREPAY) || Objects
                            .equals(amountType, OrderPayConsts.ORDER_PAY_MASTER) || Objects
                            .equals(amountType, OrderPayConsts.ORDER_PAY_DEPOSIT) || Objects
                            .equals(amountType, OrderPayConsts.ORDER_PAY_PROGRESS));
        }).collect(Collectors.toList());

        if (!payList.isEmpty()) {

            Integer depositAmount = payList.stream()
                    .filter(e -> Objects.equals(e.getDeleted(), GlobalConsts.NO))
                    .filter(e -> Objects.equals(e.getAmountType(), OrderPayConsts.ORDER_PAY_DEPOSIT))
                    .filter(e -> Objects.equals(e.getPayStatus(), PayConsts.PAY_STATUS_DONE))
                    .mapToInt(OrderPay::getAmount).sum();

            Integer unDepositAmount = payList.stream()
                    .filter(e -> Objects.equals(e.getDeleted(), GlobalConsts.NO))
                    .filter(e -> Objects.equals(e.getAmountType(), OrderPayConsts.ORDER_PAY_DEPOSIT))
                    .filter(e -> Objects.equals(e.getPayStatus(), PayConsts.PAY_STATUS_NONE))
                    .mapToInt(OrderPay::getAmount).sum();

            Integer progressAmount = payList.stream()
                    .filter(e -> Objects.equals(e.getDeleted(), GlobalConsts.NO))
                    .filter(e -> Objects.equals(e.getAmountType(), OrderPayConsts.ORDER_PAY_PROGRESS))
                    .filter(e -> Objects.equals(e.getPayStatus(), PayConsts.PAY_STATUS_DONE))
                    .mapToInt(OrderPay::getAmount).sum();

            Integer unProgressAmount = payList.stream()
                    .filter(e -> Objects.equals(e.getDeleted(), GlobalConsts.NO))
                    .filter(e -> Objects.equals(e.getAmountType(), OrderPayConsts.ORDER_PAY_PROGRESS))
                    .filter(e -> Objects.equals(e.getPayStatus(), PayConsts.PAY_STATUS_NONE))
                    .mapToInt(OrderPay::getAmount).sum();

            detailVO.setDepositAmount(depositAmount);
            detailVO.setUnDepositAmount(unDepositAmount);
            detailVO.setProgressAmount(progressAmount);
            detailVO.setUnProgressAmount(unProgressAmount);
            Integer masterAmount = Optional.ofNullable(detailVO.getMasterAmount()).orElse(0)
                    - Optional.ofNullable(unDepositAmount).orElse(0)
                    - Optional.ofNullable(unProgressAmount).orElse(0);
            detailVO.setMasterAmount(masterAmount);

            detailVO.setDiscountPrepayAmount(orderWork.getDiscountPrepayAmount());

            List<ZsOrderWorkDetailPayVO> orderWorkDetailPayList = BeanMapper.mapList(payList, ZsOrderWorkDetailPayVO.class);
            OrderWorkPositionVO positionVO = orderWorkPositionBService.getById(workId);

            orderWorkDetailPayList.forEach(e -> {
                e.setAmountTypeName(OrderPayConsts.getAmountTypeName(e.getAmountType()));
                StringBuilder payChannelNameBuilder = new StringBuilder(
                        PayConsts.getPayChannelName(e.getPayChannelId()));
                if (NumberUtil.isNotNullOrZero(e.getPayTargetChannelId())) {
                    payChannelNameBuilder.append("-").append(PayConsts.getPayChannelName(e.getPayTargetChannelId()));
                }
                if (NumberUtil.isNotNullOrZero(e.getPayType())) {
                    e.setPayTypeName(PayConsts.getPayTypeName(e.getPayType()));
                    payChannelNameBuilder.append("[" + PayConsts.getPayTypeName(e.getPayType()) + "]");
                }
                e.setPayChannelName(payChannelNameBuilder.toString());
                e.setPayStatusName(PayConsts.getPayStatusName(e.getPayStatus()));
                if (StringUtil.isNotBlank(e.getImageUrls())) {
                    e.setImgs(Arrays.stream(e.getImageUrls().split(",")).collect(Collectors.toList()));
                }
                if (Objects.equals(OrderPayConsts.ORDER_PAY_MASTER, e.getAmountType()) && positionVO != null) {
                    e.setPayDistance(positionVO.getMasterPayDistance());
                }
                if (Objects.equals(OrderPayConsts.ORDER_PAY_DEPOSIT, e.getAmountType()) && positionVO != null) {
                    e.setPayDistance(positionVO.getDepositPayDistance());
                }
                if (Objects.equals(e.getDeleted(), GlobalConsts.YES)) {
                    e.setPayStatusName("已取消");
                }
            });
            detailVO.setPayList(orderWorkDetailPayList);
        }

        //退款信息
        List<OrderPay> refundPays = orderPays.stream()
                .filter(e->Objects.equals(e.getTradeType(),PayConsts.PAY_TRADE_TYPE_REFUND) && Objects.equals(e.getDeleted(),GlobalConsts.NO))
                .collect(Collectors.toList());

        // 新单也不展示 退款信息（一口价需求 魏春淋提出）
        if (!refundPays.isEmpty() && !Objects.equals(orderWork.getType(),OrderConsts.ORDER_TYPE_COMPENSATE) && !Objects.equals(orderWork.getType(),OrderConsts.ORDER_TYPE_NEW)) {
            List<Long> orderIds = refundPays.stream()
                    .map(OrderPay::getOrderId)
                    .collect(Collectors.toList());

            List<OmsOrderReview> orderReviews = orderReviewService.getOmsOrderReviewByOrderIdsAndType(orderIds, OrderConsts.OMS_ORDER_REVIEW_REFUND);
            Map<Long, OmsOrderReview> refundReviewMap = orderReviews.stream()
                    .collect(Collectors.toMap(OmsOrderReview::getWorkId, a -> a, (k1, k2) -> k1));

            List<ZsOrderWorkDetailPayVO> orderWorkDetailRefundList = BeanMapper
                    .mapList(refundPays, ZsOrderWorkDetailPayVO.class);
            orderWorkDetailRefundList.forEach(e -> {
                OmsOrderReview orderReview = refundReviewMap.get(e.getWorkId());
                if (Objects.nonNull(orderReview)) {
                    e.setReviewStatus(orderReview.getReviewStatus());
                    e.setReviewer(orderReview.getReviewer());
                }
                e.setPayChannelName(PayConsts.getPayChannelName(e.getPayChannelId()));
                e.setPayStatusName(PayConsts.getPayStatusName(e.getPayStatus()));

                if (Objects.equals(e.getRefundType(), OrderConsts.ORDER_REFUND_TYPE_ONLINE)) {
                    e.setRefundPathName(PayConsts.getPayChannelName(e.getPayChannelId()));
                }else {
                    e.setRefundPathName(PayConsts.getPayChannelName(e.getPayTargetChannelId()));
                }
                e.setRefundTypeName(OrderConsts.getRefundTypeName(e.getRefundType()));
            });
            detailVO.setRefundList(orderWorkDetailRefundList);
        }

        // 退款审核信息->退款信息
        OmsOrderReview refundOrderReview = orderReviewService.getOmsOrderReviewByOrderIdAndWorkIdAndType(orderId, workId, OrderConsts.OMS_ORDER_REVIEW_REFUND);
        if (Objects.nonNull(refundOrderReview)
                && !Objects.equals(refundOrderReview.getReviewStatus(), OrderConsts.OMS_ORDER_REVIEW_STATUS_CHECK_SUCCESS)
                && StringUtil.isNotBlank(refundOrderReview.getReviewData())) {

            List<ZsOrderWorkDetailPayVO> zsOrderWorkDetailPayVOS = Optional.ofNullable(detailVO.getRefundList()).orElse(new ArrayList<>());
            RefundDTO refundDTO = JSON.parseObject(refundOrderReview.getReviewData(), RefundDTO.class);
            ZsOrderWorkDetailPayVO payVO = new ZsOrderWorkDetailPayVO();
            if (Objects.equals(refundOrderReview.getReviewStatus(), OrderConsts.OMS_ORDER_REVIEW_STATUS_CHECK)) {
                payVO.setPayStatusName("待退款");
            } else if (Objects.equals(refundOrderReview.getReviewStatus(), OrderConsts.OMS_ORDER_REVIEW_STATUS_CHECK_FAIL)) {
                payVO.setPayStatusName("退款失败");
            }
            if (!Objects.equals(refundDTO.getRefundType(), OrderConsts.ORDER_REFUND_TYPE_ONLINE)) {
                payVO.setRefundPathName(PayConsts.getPayChannelName(refundDTO.getPayTargetChannelId()));
                payVO.setRefundTypeName(OrderConsts.getRefundTypeName(refundDTO.getRefundType()));
            }
            payVO.setReviewStatus(refundOrderReview.getReviewStatus());
            payVO.setAmount(refundDTO.getRefundAmount());
            payVO.setPayTime(refundOrderReview.getCreateTime());
            payVO.setReviewer(refundOrderReview.getReviewer());
            zsOrderWorkDetailPayVOS.add(payVO);
            detailVO.setRefundList(zsOrderWorkDetailPayVOS);
        }

        // 工单Log
        List<OrderLog> orderLogList = orderLogBService.findOrderLogsByWorkId(workId);
        logger.debug("orderLogList===>{}",orderLogList);

        // 处理log员工部门
        processOrderLogStaffDept(orderLogList);

        // 处理log工程师信息
        processOrderLogMaster(orderLogList, orderWork.getBizType());

        // 操作数量统计
        detailVO.setLogStatList(this.getOrderLogStat(orderLogList));

        // 跟单日志
        orderLogList.addAll(orderLogBService.findNewTrackLogsByWorkId(workId));
        // 改派日志

        List<OrderRedistributeLog> redistributeLogList = orderRedistributeLogBService.findOrderLogsByWorkId(workId);
        // 处理改派申请记录的【操作人】为有【组或者部门】的样子
        orderRedistributeLogBService.processLogStaffDept(redistributeLogList);
        // 处理改派log工程师信息
        orderRedistributeLogBService.processOrderLogMaster(redistributeLogList, orderWork.getBizType());
        orderLogList.addAll(redistributeLogList);

        // 取消申请日志
        orderLogList.addAll(orderLogBService.findCancelApplyLogsByWorkId(workId));

        List<OrderLog> logList = orderLogList.stream().sorted(Comparator.comparing(OrderLog::getCreateTime).reversed())
                .collect(Collectors.toList());
        detailVO.setLogList(logList);


        processVideoRecord(orderId, detailVO);

        // 警告标识
        ZsWarningVO warningVO = findWarningByWork(orderWork, orderExtend, orderDetail);
        detailVO.setWarningVO(warningVO);

        // 厂商单信息
        if (Objects.equals(OrderConsts.ORDER_SOURCE_TYPE_FACTORY, orderWork.getSourceType())) {
            OrderFactory orderFactory = orderFactoryService.findOrderFactoryByKey(orderWork.getOrderId());
            ZsOrderWorkFactoryVO zsOrderWorkFactoryVO = BeanMapper.map(orderFactory, ZsOrderWorkFactoryVO.class);
            zsOrderWorkFactoryVO
                    .setPartReviewStatusName(OrderConsts.getReviewStatusName(orderFactory.getPartReviewStatus()));
            zsOrderWorkFactoryVO
                    .setFcPartReviewStatusName(OrderConsts.getReviewStatusName(orderFactory.getFcPartReviewStatus()));
            detailVO.setOrderFactory(zsOrderWorkFactoryVO);
            //处理厂商说明
            processChannelDescription(orderWork, detailVO, orderFactory.getFactoryId());
        } else {
            //处理渠道/用途描述
            processChannelDescription(orderWork, detailVO, null);
        }

        // 提成信息
        Long accountId = orderWork.getAccountId();
        if (NumberUtil.isNotNullOrZero(accountId)) {
            try {
                ResponseDTO<EngineerSpAccountResultDRO> responseDTO = accountDetailListRemoteService.getSpAndEngineersAccountDetailByAccountId(accountId);
                if (responseDTO.isSuccess() && responseDTO.getData() != null) {
                    EngineerSpAccountResultDRO accountDetailDRO = responseDTO.getData();
                    ZsOrderWorkCommissionVO commissionVO = BeanMapper.map(accountDetailDRO, ZsOrderWorkCommissionVO.class);
                    commissionVO.setSpReserveSettleStatusName(ErpConsts.getStatementStatus(commissionVO.getSpReserveSettleStatus()));
                    detailVO.setCommission(commissionVO);
                }
            } catch (Exception e) {
                //TODO 屏蔽ERP上线晚的错误
            }
        }

        // 完成码
        String featureCode = EncodeUtil.getFeatureCode(orderWork.getWorkId(), 4);
        detailVO.setCompleteCode(featureCode);

        //店铺信息
        OrderShop orderShop = orderShopService.findByKey(orderId);
        if (orderShop != null) {
            ZsOrderShopVO orderShopVO = BeanMapper.map(orderShop, ZsOrderShopVO.class);
            detailVO.setOrderShopVO(orderShopVO);
        }

        // 磊多多分红显示
//        List<MasterOrderBonusDRO> dmsMasterBonusList = null;
//        try {
//            dmsMasterBonusList = dmsMasterBonusDetailRemoteService.getMasterBonusRecordByOrderId(orderId).getItems();
//            logger.debug("DMS分红返回[{}]", dmsMasterBonusList);
//        } catch (Exception e) {
//            logger.error("DMS分红异常[{}]", e.getMessage(), e);
//        }
//        if (!CollectionUtils.isEmpty(dmsMasterBonusList)) {
//            Map<Integer, ZsOrderDmsMasterBonusVO> dmsMasterBonusMap = new HashMap<>();
//
//            for (MasterOrderBonusDRO obj : dmsMasterBonusList) {
//                ZsOrderDmsMasterBonusVO dmsMasterBonusVO = BeanMapper.map(obj, ZsOrderDmsMasterBonusVO.class);
//                // 分红状态名称
//                String statusName = "";
//                if (Objects.equals(MasterBonusRecordConstants.STATUS_NO_ISSUED, obj.getStatus())) {
//                    statusName = "待发奖金";
//                } else if (Objects.equals(MasterBonusRecordConstants.STATUS_ISSUED, obj.getStatus())) {
//                    statusName = "已发奖金";
//                } else if (Objects.equals(MasterBonusRecordConstants.STATUS_CANCEL, obj.getStatus())) {
//                    statusName = "奖金取消";
//                }
//                dmsMasterBonusVO.setStatusName(statusName);
//                // 工程师分组
//                if (Objects.nonNull(obj.getMasterId())) {
//                    try {
//                        logger.info("findOrderWorkDetail#getProductGroupByEngineerIdAndBizType 入参 [{}] [{}] [{}]",obj.getMasterId(),orderWork.getBizType(),orderWork.getWorkId());
//                        ResponseDTO<Option<Integer>> responseDTO = engineerCooperateInfoListRemoteService.getProductGroupByEngineerIdAndBizType(obj.getMasterId(), orderWork.getBizType());
//                        logger.info("findOrderWorkDetail#getProductGroupByEngineerIdAndBizType 出参",JSON.toJSONString(responseDTO));
//                        if (responseDTO.isSuccess() && Objects.nonNull(responseDTO.getData())){
//                            dmsMasterBonusVO.setMasterSkillGroupName(responseDTO.getData().getLabel());
//                        }
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }
//                dmsMasterBonusMap.put(obj.getMasterType(), dmsMasterBonusVO);
//            }
//
//            detailVO.setDmsMasterBonusMap(dmsMasterBonusMap);
//            logger.debug("DMS分红详情显示[{}]", dmsMasterBonusMap);
//        }

        // 预约时间，订单修改记录 xiewenbing 2019.11.27
        OrderChangeRecord changeRecord = orderChangeRecordService.getChangeRecordByOrderId(orderId);
        if (Objects.nonNull(changeRecord)) {
            ZsOrderChangeRecordVO changeRecordVO = BeanMapper.map(changeRecord, ZsOrderChangeRecordVO.class);
            detailVO.setChangeRecordVO(changeRecordVO);
        }

        // 入口名称显示
        if (!NumberUtil.isNullOrZero(orderWork.getReceiveEntranceId())) {
            detailVO.setReceiveEntranceName(
                    StringUtils.defaultString(GateTypeConsts.GATE_NAME_MAP.get(orderWork.getReceiveEntranceId())));
        }

        // 公司收款类型
        if (Objects.equals(orderWork.getPlatWork(), GlobalConsts.PLAT_MARK_YEYX) && NumberUtil
                .isNotNullOrZero(orderWork.getManageCompanyId())) {
            try {
                ResponseDTO<SpServProviderDRO> servProviderRemote = spManageListRemoteService.getServProviderById(orderWork.getManageCompanyId());
                if (servProviderRemote.isSuccess() && servProviderRemote.getData() == null) {
                    Integer balancePaymentLimit = servProviderRemote.getData().getBalancePaymentLimit();
                    String balancePaymentLimitName = "";
                    if (Objects.equals(balancePaymentLimit, 1)) {
                        balancePaymentLimitName = "公司收尾款";
                    } else if (Objects.equals(balancePaymentLimit, 2)) {
                        balancePaymentLimitName = "公司不收尾款";
                    } else if (Objects.equals(balancePaymentLimit, 3)) {
                        balancePaymentLimitName = "";
                    }
                    detailVO.setBalancePaymentLimitName(balancePaymentLimitName);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //快递物流信息
        List<OrderPost> orderPostList = orderPostService.listOrderPostByOrderId(orderId);
        logger.debug("orderPostList:{}", orderPostList);
        if (CollectionUtil.isNotNullOrEmpty(orderPostList)) {
            List<OrderPostVO> orderPostVOList = BeanMapper.mapList(orderPostList, OrderPostVO.class);
            orderPostVOList.forEach(orderPost -> {
                orderPost.setItemTypeName(OrderPostConsts.getExpressItemTypeName(orderPost.getItemType()));
                orderPost.setStatusName(OrderPostConsts.getPostStatusName(orderPost.getStatus()));
            });
            detailVO.setOrderPostVOList(orderPostVOList);
        }

        // 厂商配件快递信息
        List<ZsOrderWorkFactoryPartVO> factoryPartList = detailVO.getFactoryPartList();
        logger.debug("factoryPartList:{}", factoryPartList);
        if (!CollectionUtils.isEmpty(factoryPartList)) {
            factoryPartList.forEach(zsOrderWorkFactoryPartVO -> {
                List<ZsOrderWorkFactoryPartPostVO> factoryPartPostList = zsOrderWorkFactoryPartVO.getFactoryPartPostList();
                if (!CollectionUtils.isEmpty(factoryPartPostList)) {
                    List<OrderPostVO> orderPostVOList = Lists.newArrayList();
                    factoryPartPostList.forEach(partPost -> {
                        OrderPostVO postVO = new OrderPostVO();
                        postVO.setExpressCode(partPost.getExpressCode());
                        postVO.setStatusName(partPost.getPostStatusName());
                        postVO.setExpressCompany(partPost.getExpressCompany());
                        postVO.setExpressData(partPost.getExpressData());
                        postVO.setReceiver(partPost.getConsigneeName() + "-" + partPost.getConsigneePhone());
                        postVO.setReceiveAddress(partPost.getAddress());
                        postVO.setItemTypeName(partPost.getPostTypeName());
                        orderPostVOList.add(postVO);
                    });

                    if (CollectionUtils.isEmpty(detailVO.getOrderPostVOList())) {
                        detailVO.setOrderPostVOList(orderPostVOList);
                    } else {
                        detailVO.getOrderPostVOList().addAll(orderPostVOList);
                    }
                }
            });
        }

        // 运营责任人
        processAbutmenterName(orderWork, detailVO);

        // 渠道处理
        processChannel(orderWork, detailVO);

        // 来源渠道
        processSourceChannel(orderWork, detailVO);

        processCompanyInfo(orderWork, orderDetail, detailVO);

        processChannelDockingLog(orderWork, detailVO);

        // 处理结算价
        processSettlementPrice(orderWork, detailVO, orderProductList);

        // 处理渠道结算信息
        processChannelStatement(orderWork, detailVO);

        // 处理下单用户信息
        OrderUserDetailDTO userInfo = orderBService.getUserInfo(orderDetail.getUserType(), orderWork.getUserId());
        if (Objects.nonNull(userInfo)){
            ZsOrderWorkDetailUserInfoVO userInfoVO = ZsOrderWorkDetailUserInfoVO.builder().gender(userInfo.getGender()).genderName(GlobalDict.getGender(Optional.ofNullable(userInfo.getGender()).orElse(0)))
                    .mobile(userInfo.getMobile()).userName(userInfo.getUserName()).passId(userInfo.getPassId()).build();
            detailVO.setUserInfoVO(userInfoVO);
        }

        // 挂起/失败原因
        if (Objects.equals(orderWork.getDutyStatus(), OrderDutyConsts.DUTY_STATUS_FAIL) ||
                Objects.equals(orderWork.getDutyStatus(), OrderDutyConsts.DUTY_STATUS_SUSPEND)) {
            StringBuilder sb = new StringBuilder();
            if (Objects.equals(orderWork.getDutyStatus(), OrderDutyConsts.DUTY_STATUS_FAIL)) {
                sb.append(OrderDutyConsts.getDutyFailedReasonName(orderWork.getDutyFailCode()));
            } else if (Objects.equals(orderWork.getDutyStatus(), OrderDutyConsts.DUTY_STATUS_SUSPEND)) {
                sb.append(OrderDutyConsts.getDutySuspendReasonName(orderWork.getDutyFailCode()));
            }
            OrderRemark orderRemark = orderRemarkService.findByOrderIdAndType(orderId, workId, OrderConsts.ORDER_REMARK_TYPE_SUSPEND);
            if (Objects.nonNull(orderRemark)) {
                sb.append(orderRemark.getContent());
            }
            detailVO.setDutyFailContent(sb.toString());
        }

        // 是否有分润预估
        detailVO.setHaveSharingEstimate(orderWorkERPQueryBService.haveSharingEstimate(orderWork));

        // 详情展示网格信息
        if (zsDistributeWorkBService.isGridDistribute(orderWork)){
            detailVO.setGrid(true);
            if (Objects.equals(orderDetail.getGridId(), GlobalConsts.NONE)){
                detailVO.setGridInfo("当前位置无网格覆盖");
            } else {
                detailVO.setGridInfo(String.format("%s/%s", orderDetail.getGridName(), orderDetail.getGridId()));
            }
        }

        // 赔偿金额
        OrderWorkQuery esQuery = new OrderWorkQuery();
        esQuery.setOrderId(orderId);
        esQuery.setSingleWorkType(OrderConsts.ORDER_TYPE_COMPENSATE);
        esQuery.setWorkStatus(Lists.newArrayList(OrderStatusConsts.WORK_STATUS_COMPLETE,OrderStatusConsts.WORK_STATUS_CHECKOUT,OrderStatusConsts.WORK_STATUS_ACCOUNT));
        List<EsOrderWork> esOrderWorks = orderWorkListBService.listPageOrderWorkByQuery(esQuery);
        if (CollectionUtil.isNotNullOrEmpty(esOrderWorks)) {
            Integer compensateAmount = null;
            if (Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_NEW)) {
                if (CollectionUtil.isNotNullOrEmpty(esOrderWorks)) {
                    compensateAmount = esOrderWorks.stream()
                            .mapToInt(EsOrderWork::getTotalAmount)
                            .sum();

                }
            }else if (Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_COMPENSATE)) {
                compensateAmount = esOrderWorks.stream()
                        .filter(e -> Objects.equals(e.getId(), workId))
                        .mapToInt(EsOrderWork::getTotalAmount)
                        .sum();
            }

            if (!NumberUtil.isNullOrZero(compensateAmount)) {
                compensateAmount = Math.abs(compensateAmount);
                detailVO.setCompensateAmount(compensateAmount);
            }
        }

        if (!isRefundOrCompensateOrder) {
            // 责任工程师
            if (changeRecord != null && NumberUtil.isNotNullOrZero(changeRecord.getCancelLiableMasterId())) {

                try {
                    logger.debug("findOrderWorkDetail#getEngineerDetailById 入参 [{}]",changeRecord.getCancelLiableMasterId());
                    ResponseDTO<ForeignEngineerDetailInfoDRO> engineerByEngineerId = engineerListRemoteService.getEngineerDetailById(changeRecord.getCancelLiableMasterId());
                    logger.debug("findOrderWorkDetail#getEngineerDetailById 出参 [{}]",JSON.toJSONString(engineerByEngineerId));
                    ForeignEngineerDetailInfoDRO data = engineerByEngineerId.getData();
                    if (data != null) {
                        LiableMasterVO liableMasterVO = new LiableMasterVO();
                        liableMasterVO.setMasterId(data.getEngineerId());
                        liableMasterVO.setMasterName(data.getRealName());
                        liableMasterVO.setMasterPhone(data.getMobile());
                        liableMasterVO.setHierarchyLevel(data.getHierarchyLevel());

                        if (CollectionUtil.isNotNullOrEmpty(data.getCooperateInfoList())) {
                            ForeignEngineerCooperateInfoDRO engineerCooperateInfoDRO = data.getCooperateInfoList().stream().filter(info -> Objects.equals(info.getBizType(), orderWork.getBizType())).findFirst().orElse(null);
                            if (Objects.nonNull(engineerCooperateInfoDRO)) {
                                liableMasterVO.setGroupName(StringUtils.defaultString(engineerCooperateInfoDRO.getProductGroupName()));
                            }
                        }

                        /*logger.debug("findOrderWorkDetail#getProductGroupByEngineerIdAndBizType 入参 [{}] [{}] [{}]",data.getEngineerId(),orderWork.getBizType(),orderWork.getWorkId());
                        ResponseDTO<Option<Integer>> responseDTO = engineerCooperateInfoListRemoteService.getProductGroupByEngineerIdAndBizType(data.getEngineerId(), orderWork.getBizType());
                        logger.debug("findOrderWorkDetail#getProductGroupByEngineerIdAndBizType 出参 [{}]",JSON.toJSONString(responseDTO));
                        if (responseDTO.isSuccess() && Objects.nonNull(responseDTO.getData())) {
                            liableMasterVO.setGroupName(StringUtils.defaultString(responseDTO.getData().getLabel()));
                        }*/
                        detailVO.setLiableMaster(liableMasterVO);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else if (CollectionUtils.isNotEmpty(detailVO.getMasterVOList())) {
                // 没有责任工程师的时候，主工程师就是责任工程师
                ZsOrderWorkDetailMasterVO zsOrderWorkDetailMasterVO = detailVO.getMasterVOList().stream()
                        .filter(item -> Objects.equals(item.getType(), OrderConsts.ORDER_MASTER_TYPE_MAIN)).findAny().orElse(null);
                if(zsOrderWorkDetailMasterVO != null){
                    LiableMasterVO liableMasterVO = new LiableMasterVO();
                    liableMasterVO.setMasterId(zsOrderWorkDetailMasterVO.getMasterId());
                    liableMasterVO.setMasterName(zsOrderWorkDetailMasterVO.getMasterName());
                    liableMasterVO.setMasterPhone(zsOrderWorkDetailMasterVO.getMasterPhone());
                    liableMasterVO.setGroupName(zsOrderWorkDetailMasterVO.getMasterGroupName());
                    liableMasterVO.setHierarchyLevel(zsOrderWorkDetailMasterVO.getHierarchyLevel());
                    detailVO.setLiableMaster(liableMasterVO);
                }
            }
        }

        if (CollectionUtil.isNotNullOrEmpty(detailVO.getMasterVOList())) {
            List<ZsOrderWorkDetailMasterVO> mainMasterVOList = detailVO.getMasterVOList().stream()
                    .filter(item -> Objects.equals(item.getType(), OrderConsts.ORDER_MASTER_TYPE_MAIN))
                    .collect(Collectors.toList());

            List<ZsOrderWorkDetailMasterVO> slaveMasterVOList = detailVO.getMasterVOList().stream()
                    .filter(item -> Objects.equals(item.getType(), OrderConsts.ORDER_MASTER_TYPE_SLAVE))
                    .collect(Collectors.toList());

            detailVO.setMainMasterVOList(mainMasterVOList);
            detailVO.setSlaveMasterVOList(slaveMasterVOList);
        }

        // 处理过保新单
        if (Objects.equals(OrderConsts.ORDER_TYPE_NEW, orderWork.getType())) {
            OrderWorkRelation orderWorkRelation = workRelationService.findOrderWorkRelationByOrderIdAndWorkId(orderId, workId,
                    OrderConsts.WORK_RELATION_TYPE_NEW_INSURANCE_FORM);
            if (Objects.nonNull(orderWorkRelation)) {
                OrderWorkRelationVO workRelationVO = new OrderWorkRelationVO();
                BeanUtils.copyProperties(orderWorkRelation, workRelationVO);
                detailVO.setWorkRelationVO(workRelationVO);
            }
        }

        processTimesCardRefundAmount(detailVO);

        // 新单时，获取关联订单数量
        if (Objects.equals(OrderConsts.ORDER_TYPE_NEW, orderWork.getType())) {
            detailVO.setRelationOrderWorkCountVO(this.getRelationOrderWorkCountVO(workId));
        }
        detailVO.setChannelPrepayAmountDetail(processChannelPrepayList(orderWork));

        // 获取支付优惠
        this.getOrderPayDiscountList(detailVO);

        // 常见备注
        OrderRemark orderRemark = orderRemarkService.findByOrderIdAndType(orderId, workId, OrderConsts.ORDER_REMARK_TYPE_INPUT);
        if (Objects.nonNull(orderRemark)) {
            detailVO.setCommonRemark(orderRemark.getContent());
        }

        return detailVO;
    }

    @Override
    public OrderIncomeDetailDRO findOrderIncomeDetail(Long orderId, Long workId) {
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);
        OrderIncomeDetailDRO orderIncomeDetailDRO = new OrderIncomeDetailDRO();
        orderIncomeDetailDRO.setChannelPrepayAmount(orderWork.getChannelPrepayAmount());
        orderIncomeDetailDRO.setChannelPrepayAmountPayStatusName(Objects.nonNull(orderWork.getChannelPrepayAmount()) ? PayConsts.getPayStatusName(orderWork.getChannelPrepayStatus()) : "");
        orderIncomeDetailDRO.setChannelPrepayAmountDetail(processChannelPrepayList(orderWork));
        orderIncomeDetailDRO.setPrepayAmount(orderWork.getPrepayAmount());
        orderIncomeDetailDRO.setMasterAmount(orderWork.getMasterAmount());
        orderIncomeDetailDRO.setPrepayAmountPayStatusName(Objects.nonNull(orderWork.getPrepayAmount()) ? (Objects.equals(0, orderWork.getPrepayStatus()) ? "未支付" : PayConsts.getPayStatusName(orderWork.getPrepayStatus())) : "");
        orderIncomeDetailDRO.setDepositAmountPayStatusName(Objects.nonNull(orderWork.getDepositAmount()) ? PayConsts.getPayStatusName(orderWork.getDepositStatus()) : "");
        orderIncomeDetailDRO.setMasterAmountPayStatusName(Objects.nonNull(orderWork.getMasterAmount()) ? PayConsts.getPayStatusName(orderWork.getMasterPayStatus()) : "");
        Integer onlyVisit = orderWork.getOnlyVisit();
        if (onlyVisit == GlobalConsts.YES) {
            orderIncomeDetailDRO.setHomeAmount(orderIncomeDetailDRO.getMasterAmount());
            orderIncomeDetailDRO.setMasterAmount(null);
        }
        // 支付信息
        List<OrderPay> orderPays = orderPayService.listAllOrderPayByOrderIdAndWorkId(orderId, workId);
        List<OrderPay> payList = orderPays.stream().filter(e -> {
            Integer amountType = e.getAmountType();
            Integer tradeType = e.getTradeType();
            return Objects.equals(tradeType, PayConsts.PAY_TRADE_TYPE_INTIME) && (
                    Objects.equals(amountType, OrderPayConsts.ORDER_PAY_PREPAY) || Objects
                            .equals(amountType, OrderPayConsts.ORDER_PAY_MASTER) || Objects
                            .equals(amountType, OrderPayConsts.ORDER_PAY_DEPOSIT) || Objects
                            .equals(amountType, OrderPayConsts.ORDER_PAY_PROGRESS));
        }).collect(Collectors.toList());
        if (!payList.isEmpty()) {
            Integer depositAmount = payList.stream()
                    .filter(e -> Objects.equals(e.getDeleted(), GlobalConsts.NO))
                    .filter(e -> Objects.equals(e.getAmountType(), OrderPayConsts.ORDER_PAY_DEPOSIT))
                    .filter(e -> Objects.equals(e.getPayStatus(), PayConsts.PAY_STATUS_DONE))
                    .mapToInt(OrderPay::getAmount).sum();

            Integer unDepositAmount = payList.stream()
                    .filter(e -> Objects.equals(e.getDeleted(), GlobalConsts.NO))
                    .filter(e -> Objects.equals(e.getAmountType(), OrderPayConsts.ORDER_PAY_DEPOSIT))
                    .filter(e -> Objects.equals(e.getPayStatus(), PayConsts.PAY_STATUS_NONE))
                    .mapToInt(OrderPay::getAmount).sum();

            Integer progressAmount = payList.stream()
                    .filter(e -> Objects.equals(e.getDeleted(), GlobalConsts.NO))
                    .filter(e -> Objects.equals(e.getAmountType(), OrderPayConsts.ORDER_PAY_PROGRESS))
                    .filter(e -> Objects.equals(e.getPayStatus(), PayConsts.PAY_STATUS_DONE))
                    .mapToInt(OrderPay::getAmount).sum();

            Integer unProgressAmount = payList.stream()
                    .filter(e -> Objects.equals(e.getDeleted(), GlobalConsts.NO))
                    .filter(e -> Objects.equals(e.getAmountType(), OrderPayConsts.ORDER_PAY_PROGRESS))
                    .filter(e -> Objects.equals(e.getPayStatus(), PayConsts.PAY_STATUS_NONE))
                    .mapToInt(OrderPay::getAmount).sum();

            orderIncomeDetailDRO.setDepositAmount(depositAmount);
            orderIncomeDetailDRO.setUnDepositAmount(unDepositAmount);
            orderIncomeDetailDRO.setProgressAmount(progressAmount);
            orderIncomeDetailDRO.setUnProgressAmount(unProgressAmount);
            Integer masterAmount = Optional.ofNullable(orderIncomeDetailDRO.getMasterAmount()).orElse(0)
                    - Optional.ofNullable(unDepositAmount).orElse(0)
                    - Optional.ofNullable(unProgressAmount).orElse(0);
            orderIncomeDetailDRO.setMasterAmount(masterAmount);

            orderIncomeDetailDRO.setDiscountPrepayAmount(orderWork.getDiscountPrepayAmount());
        }

        // 次卡
        if (NumberUtil.isNotNullOrZero(orderWork.getDiscountPrepayAmount())) {
            List<OrderDiscount> orderDiscountList = orderDiscountService.listByOrderId(orderId).stream()
                    .filter(e -> Objects.equals(e.getCateg(), DiscountTypeEnums.DISCOUNT_COUP_ONCECARD.getSubType()))
                    .collect(Collectors.toList());
            if (CollectionUtil.isNotNullOrEmpty(orderDiscountList)) {
                ResponseDTO<OrderTimesCardDRO> coupResponseDTO = null;
                try {
                    coupResponseDTO = vasOrderTimesCardListRemoteService.getOrderTimesCardByCouponCode(orderDiscountList.get(0).getItemCode());
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
                logger.debug("退款查询次卡信息 入参：{} 出参：{}", orderDiscountList.get(0).getItemCode(), JSON.toJSONString(coupResponseDTO));
                if (coupResponseDTO.isSuccess()) {
                    OrderTimesCardDRO dro = coupResponseDTO.getData();
                    orderIncomeDetailDRO.setDiscountPrepayRefundAmount(dro.getRefundAmount());
                }
            }
        }
        orderIncomeDetailDRO.setRefundAmount(orderWork.getRefundAmount());
        return orderIncomeDetailDRO;
    }

    /**
     * 获取关联订单数量
     *
     * @param workId
     * @return
     */
    private RelationOrderWorkCountVO getRelationOrderWorkCountVO(Long workId) {
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery()
                .filter(QueryBuilders.termQuery("originalId", workId));

        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        NativeSearchQuery build = nativeSearchQueryBuilder.withQuery(queryBuilder)
                .withPageable(Pageable.unpaged())
                // 返修单
                .addAggregation(AggregationBuilders.filter("reworkOrderCount", QueryBuilders.boolQuery()
                        .filter(QueryBuilders.termQuery("type", OrderConsts.ORDER_TYPE_REWORK))))
                // 退款单
                .addAggregation(AggregationBuilders.filter("refundOrderCount", QueryBuilders.boolQuery()
                        .filter(QueryBuilders.termQuery("type", OrderConsts.ORDER_TYPE_REFUND))))
                // 赔偿单
                .addAggregation(AggregationBuilders.filter("compensateOrderCount", QueryBuilders.boolQuery()
                        .filter(QueryBuilders.termQuery("type", OrderConsts.ORDER_TYPE_COMPENSATE))))
                .build();

        Aggregations aggregations = orderWorkEsBService.getAggregationsByQuery(build);
        RelationOrderWorkCountVO obj = new RelationOrderWorkCountVO();
        // 返修单
        Long reworkOrderCount = ((ParsedFilter) aggregations.get("reworkOrderCount")).getDocCount();
        obj.setReworkOrderCount(reworkOrderCount.intValue());
        // 退款单
        Long refundOrderCount = ((ParsedFilter) aggregations.get("refundOrderCount")).getDocCount();
        obj.setRefundOrderCount(refundOrderCount.intValue());
        // 赔偿单
        Long compensateOrderCount = ((ParsedFilter) aggregations.get("compensateOrderCount")).getDocCount();
        obj.setCompensateOrderCount(compensateOrderCount.intValue());

        return obj;
    }

    private void processVideoRecord(Long orderId, ZsOrderWorkDetailVO detailVO) {
        // logger.info("sourceVideoRecordListRemoteService.listValidRecords params: orderId={},type={}", orderId, ServiceIdTypeEnum.ORDER_ID.getCode());
        ResponseDTO<List<PlayVideoRecordDRO>> listValidRecords = null;
        try {
            listValidRecords = sourceVideoRecordListRemoteService.listValidRecords(String.valueOf(orderId), ServiceIdTypeEnum.ORDER_ID.getCode(), null);
        } catch (Exception e) {
            logger.error("sourceVideoRecordListRemoteService.listValidRecords error:{}", e.getMessage());
            return;
        }
        // logger.info("sourceVideoRecordListRemoteService.listValidRecords result:{}", listValidRecords);
        if (listValidRecords.isSuccess() && CollectionUtil.isNotNullOrEmpty(listValidRecords.getData())) {
            List<ZsOrderWorkVideoRecord> videoRecords = new ArrayList<>(listValidRecords.getData().size());
            for (PlayVideoRecordDRO dro : listValidRecords.getData()) {
                ZsOrderWorkVideoRecord record = new ZsOrderWorkVideoRecord();
                record.setVideoPlayNumber(dro.getSeq());
                record.setVideoName(dro.getTitle());
                record.setPlayTime(dro.getPlayDuration());
                record.setTriggerWay(VideoPlayTypeEnum.getName(dro.getPlayType()));
                record.setPlayStartDate(dro.getStartTime());
                record.setPlayEndDate(dro.getEndTime());
                videoRecords.add(record);
            }
            detailVO.setCmsVideoRecord(videoRecords);
        }
    }

    /**
     * 处理渠道可结算时间
     *
     * @param orderWork
     * @param detailVO
     */
    private void processChannelStatement(OrderWork orderWork, ZsOrderWorkDetailVO detailVO) {
        OrderStatement orderStatement = orderStatementService.findOrderStatementByOrderId(orderWork.getOrderId(), orderWork.getWorkId());
        if (Objects.isNull(orderStatement)) {
            return;
        }
        detailVO.setChannelStatementCanTime(orderStatement.getChannelStatementCanTime());
    }

    /**
     * 获取业务线名称
     *
     * @param orderWork
     * @param detailVO
     */
    private void processBizLineName(OrderWork orderWork, ZsOrderWorkDetailVO detailVO) {
        if (NumberUtil.isNullOrZero(orderWork.getBizLine())) {
            return;
        }
        try {
            //logger.info("{} 获取业务线名称#productBusinessLineListRemoteService.getOptionNameById bizLine={}", orderWork.getWorkId(), orderWork.getBizLine());
            ResponseDTO<Option<Integer>> nameVtResponseDto = productBusinessLineListRemoteService.getOptionNameById(orderWork.getBizLine());
            //logger.info("{} 获取业务线名称#productBusinessLineListRemoteService.getOptionNameById nameVtResponseDto={}", orderWork.getWorkId(), nameVtResponseDto);
            Option<Integer> vtDTO = nameVtResponseDto.getData();
            if (Objects.nonNull(vtDTO)) {
                detailVO.setBizLineName(vtDTO.getLabel());
            }
        } catch (Exception ex) {
            logger.warn("工单[{}] 查询业务线信息失败：{}", orderWork.getOrderId(), ex);
        }
    }

    /**
     * 获取渠道对接交互日志
     *
     * @param orderWork
     * @param detailVO
     */
    private void processChannelDockingLog(OrderWork orderWork, ZsOrderWorkDetailVO detailVO) {
        List<OrderChannelDockingLog> dockingLogs =
                orderChannelDockingLogBService.listByOrderIdAndChannelId(orderWork.getOrderId(), orderWork.getChannelId());
        if (CollectionUtils.isEmpty(dockingLogs)) {
            return;
        }

        List<OrderChannelDockingLogVO> dockingLogVOs = dockingLogs.stream().map(item -> {
            OrderChannelDockingLogVO logVO = BeanMapper.map(item, OrderChannelDockingLogVO.class);

            TodmConsts.DockingInfo dockingInfo = TodmConsts.getDockingInfo(item.getOperation());
            if (dockingInfo == null) {
                return null;
            }
            logVO.setTypeIcon(dockingInfo.getTypeIcon());
            logVO.setOperationName(dockingInfo.getOperationName());

            String beginTimeStr = String.valueOf(item.getBeginTime());
            if (beginTimeStr.length() > 14) {
                logVO.setBeginTimeStr(String.format("%s-%s-%s %s:%s:%s.%s",
                        beginTimeStr.substring(0, 4),
                        beginTimeStr.substring(4, 6),
                        beginTimeStr.substring(6, 8),
                        beginTimeStr.substring(8, 10),
                        beginTimeStr.substring(10, 12),
                        beginTimeStr.substring(12, 14),
                        beginTimeStr.substring(14)
                ));
            }
            else {
                logVO.setBeginTimeStr(beginTimeStr);
            }

            String endTimeStr = String.valueOf(item.getEndTime());
            if (endTimeStr.length() > 14) {
                logVO.setEndTimeStr(String.format("%s-%s-%s %s:%s:%s.%s",
                        endTimeStr.substring(0, 4),
                        endTimeStr.substring(4, 6),
                        endTimeStr.substring(6, 8),
                        endTimeStr.substring(8, 10),
                        endTimeStr.substring(10, 12),
                        endTimeStr.substring(12, 14),
                        endTimeStr.substring(14)
                ));
            }
            else {
                logVO.setEndTimeStr(endTimeStr);
            }

            return logVO;
        }).collect(Collectors.toList());

        detailVO.setDockingLogList(dockingLogVOs);
    }

    /**
     * 获取公司信息
     * @return
     */
    private void processCompanyInfo(OrderWork orderWork, OrderDetail orderDetail, ZsOrderWorkDetailVO detailVO) {
        if (NumberUtil.isNotNullOrZero(orderWork.getManageCompanyId())) {
            // 服务公司
            ResponseDTO<CompanyContactDRO> companyByCompanyId = null;
            try {
                companyByCompanyId = companyListRemoteService
                        .getCompanyContactDROById(orderWork.getManageCompanyId());
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }
            // 获取公司信息
            if (!companyByCompanyId.isSuccess() || Objects.isNull(companyByCompanyId.getData())) {
                logger.error("获取公司信息异常[{}]", companyByCompanyId.getMessage());
                return;
            } else {
                logger.info("获取公司信息出参[{}]", companyByCompanyId);
                String servicePhone = companyByCompanyId.getData().getServicePhone();
                detailVO.setServicePhone(servicePhone);
            }
        }

        if (NumberUtil.isNotNullOrZero(orderDetail.getGridManageCompanyId())) {
            // 执行服务公司
            try {
                ResponseDTO<CompanyContactDRO> companyByCompanyId = companyListRemoteService
                        .getCompanyContactDROById(orderDetail.getGridManageCompanyId());
                // 获取公司信息
                if (!companyByCompanyId.isSuccess() || Objects.isNull(companyByCompanyId.getData())) {
                    logger.error("获取公司信息异常[{}]", companyByCompanyId.getMessage());
                    return;
                } else {
                    logger.info("获取公司信息出参[{}]", companyByCompanyId);
                    String servicePhone = companyByCompanyId.getData().getServicePhone();
                    detailVO.setGridManageCompanyServicePhone(servicePhone);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 处理订单 log 员工数据
     * @param orderLogList
     */
    private void processOrderLogStaffDept(List<OrderLog> orderLogList) {

        if (CollectionUtils.isEmpty(orderLogList)) {
            return;
        }

        // 员工Id集合
        List<Integer> staffIds = orderLogList.stream().filter(e -> e.getOperatorId() < Integer.MAX_VALUE && (
                Objects.equals(e.getOperatorType(), GlobalConsts.OPERATE_USER_TYPE_STAFF) || Objects
                        .equals(e.getOperatorType(), GlobalConsts.OPERATE_USER_TYPE_MASTER)))
                .filter(e->Objects.nonNull(e.getOperatorId()))
                .map(e -> e.getOperatorId().intValue()).distinct().collect(Collectors.toList());
        if (CollectionUtils.isEmpty(staffIds)) {
            return;
        }

        // 员工集合组装部门数据
        ResponseDTO<List<StaffDRO>> staffList = null;
        try {
            staffList = staffListRemoteService.listStaffByStaffIds(staffIds, null);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        if (CollectionUtils.isEmpty(staffList.getData())) {
            return;
        }

        staffList.getData().forEach(e -> e.setDeptName(StringUtils.defaultString(e.getDeptName())));
        // 拼装员工部门
        Map<Integer, String> staffDeptMap = staffList.getData().stream().collect(Collectors.toMap(StaffDRO::getStaffId, StaffDRO::getDeptName));
        orderLogList.forEach(e -> {
            if (staffDeptMap.containsKey(e.getOperatorId().intValue())) {
                String deptName = staffDeptMap.get(e.getOperatorId().intValue());
                if (StringUtil.isNotBlank(e.getOperator())) {
                    e.setOperator(deptName + "-" + e.getOperator());
                } else {
                    e.setOperator(deptName);
                }
            }
        });
    }

    /**
     * 获取下单渠道
     *
     * @return
     */
    private void processChannel(OrderWork orderWork, ZsOrderWorkDetailVO detailVO) {
        if (NumberUtil.isNullOrZero(orderWork.getChannelTwoId())) {
            return;
        }
        detailVO.setChannelTwoId(orderWork.getChannelTwoId());

        ResponseDTO<ChannelDRO> channelResponseDTO = null;
        try {
            channelResponseDTO = channelListRemoteService.getByChannelId(orderWork.getChannelTwoId());
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        ChannelDRO channelResponseDTOData = channelResponseDTO.getData();
        if (Objects.nonNull(channelResponseDTOData)) {
            detailVO.setChannelTwoName(channelResponseDTOData.getName());
            // 推广品牌
            if (NumberUtil.isNotNullOrZero(channelResponseDTOData.getPromotionBrand())) {
                detailVO.setPromotionBrand(channelResponseDTOData.getPromotionBrand() == GlobalConsts.PLAT_MARK_ZMN ? "啄木鸟" : "非啄木鸟");
            } else {
                detailVO.setPromotionBrand("无");
            }
        }
    }

    private void processAbutmenterName(OrderWork orderWork, ZsOrderWorkDetailVO detailVO){
        if (NumberUtil.isNullOrZero(orderWork.getChannelId())) {
            return;
        }
        try {
            ResponseDTO<ChannelDRO> channelResponseDTO = channelListRemoteService.getByChannelId(orderWork.getChannelId());
            ChannelDRO data = channelResponseDTO.getData();
            if (Objects.isNull(data)) {
                return;
            }
            detailVO.setAbutmenterName(data.getAbutmenterName());
        } catch (Exception e) {
            logger.error("channelListRemoteService.getByChannelId channelId={},error={}", orderWork.getChannelId(), e.getMessage());
        }
    }

    /**
     * 获取来源渠道
     *
     * @return
     */
    private void processSourceChannel(OrderWork orderWork, ZsOrderWorkDetailVO detailVO) {

        Integer sourceChannelId = orderWork.getSourceChannelId();
        detailVO.setSourceChannelId(sourceChannelId);

        // 如果没有来源渠道 则忽略
        if (NumberUtil.isNullOrZero(sourceChannelId)) {
            return;
        }

        try {
            com.zmn.common.dto2.ResponseDTO<ChannelDRO> sourceChannelResponseDTO = channelListRemoteService.getByChannelId(sourceChannelId);
            logger.info("#oms#订单号={}，获取来源渠道信息入参{},出参【{}】", orderWork.getOrderId(), sourceChannelId, JSON.toJSONString(sourceChannelResponseDTO));
            if (!sourceChannelResponseDTO.isSuccess() || Objects.isNull(sourceChannelResponseDTO.getData())) {
                logger.error("#oms#orderdetail#来源渠道不存在{}#{} ", orderWork.getWorkId(), sourceChannelResponseDTO.toString());
                return;
            }
            ChannelDRO channelDRO= sourceChannelResponseDTO.getData();
            detailVO.setSourceChannelName(channelDRO.getName());
            detailVO.setSourceChannelTwoId(channelDRO.getParentSourceId());
            detailVO.setSourceChannelTwoName(channelDRO.getParentSourceName());
            // 推广品牌
            if (NumberUtil.isNotNullOrZero(channelDRO.getPromotionBrand())) {
                detailVO.setPromotionBrand(channelDRO.getPromotionBrand() == GlobalConsts.PLAT_MARK_ZMN ? "啄木鸟" : "非啄木鸟");
            } else {
                detailVO.setPromotionBrand("无");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        // 渠道扩展数据
        {
            // 智米-需要补充智米订单类型，师傅客户端需要该字段显示对应的输入框，补充智米指定的数据
            if (Objects.equals(ZhimiConsts.CHANNEL_ID, orderWork.getChannelId())) {
                ZhimiOrderExtend zhimiOrderExtend = zhimiOrderExtendService
                        .findZhimiOrderExtend(orderWork.getOrderId(), false);
                if (zhimiOrderExtend != null) {
                    detailVO.setZhimiServiceType(zhimiOrderExtend.getServiceType());
                }
            }
        }
    }

    /**
     * 处理订单log 工程师数据
     * @param orderLogList
     */
    private void processOrderLogMaster(List<OrderLog> orderLogList, Integer bizType) {

        if (CollectionUtils.isEmpty(orderLogList)) {
            return;
        }

        // 工程师Id集合
        List<Integer> masterIds = orderLogList.stream().filter(e -> e.getOperatorId() < Integer.MAX_VALUE && Objects
                .equals(e.getOperatorType(), GlobalConsts.OPERATE_USER_TYPE_MASTER))
                .map(e -> e.getOperatorId().intValue()).distinct().collect(Collectors.toList());
        if (CollectionUtils.isEmpty(masterIds)) {
            return;
        }

        // 处理工程师 分组数据
        orderLogList.forEach(e -> {
            if (!Objects.equals(e.getOperatorType(), GlobalConsts.OPERATE_USER_TYPE_MASTER)){
                return;
            }

            try {
                logger.debug("processOrderLogMaster#getProductGroupByEngineerIdAndBizType 入参 [{}] [{}]", e.getOperatorId().intValue(), bizType);
                ResponseDTO<Option<Integer>> responseDTO = engineerCooperateInfoListRemoteService.getProductGroupByEngineerIdAndBizType(e.getOperatorId().intValue(), bizType);
                logger.debug("processOrderLogMaster#getProductGroupByEngineerIdAndBizType 出参 [{}]",JSON.toJSONString(responseDTO));
                if (responseDTO.isSuccess() && Objects.nonNull(responseDTO.getData())) {
                    String masterSkillGroupName = responseDTO.getData().getLabel();
                    if (StringUtil.isNotBlank(masterSkillGroupName)) {
                        e.setOperator(StringUtils.defaultString(masterSkillGroupName) + "-" + e.getOperator());
                    }
                }
            } catch (Exception ex) {
            }

        });
    }

    /**
     * log统计
     * @param orderLogList
     */
    private List<LogStatVO> getOrderLogStat(List<OrderLog> orderLogList) {
        if (CollectionUtils.isEmpty(orderLogList)) {
            return Lists.newArrayList();
        }

        // 操作员日志数量统计
        Map<Integer, Long> optCountMap = orderLogList.stream().collect(Collectors.groupingBy(o -> Optional.ofNullable(o.getOperatorType()).orElse(GlobalConsts.OPERATE_USER_TYPE_SYSTEM), Collectors.counting()));
        // 总数
        List<LogStatVO> logStatList = Lists.newArrayListWithExpectedSize(5);
        logStatList.add(LogStatVO.builder()
                .operatorType(0)
                .operatorTypeName("总数")
                .operateCount(orderLogList.size()).build());
        // 员工
        int staffOptCount = optCountMap.containsKey(GlobalConsts.OPERATE_USER_TYPE_STAFF) ? optCountMap.get(GlobalConsts.OPERATE_USER_TYPE_STAFF).intValue() : 0;
        logStatList.add(LogStatVO.builder()
                .operatorType(GlobalConsts.OPERATE_USER_TYPE_STAFF)
                .operatorTypeName(GlobalConsts.getOperatorTypeName(GlobalConsts.OPERATE_USER_TYPE_STAFF))
                .operateCount(staffOptCount).build());

        // 工程师
        int masterOptCount = optCountMap.containsKey(GlobalConsts.OPERATE_USER_TYPE_MASTER) ? optCountMap.get(GlobalConsts.OPERATE_USER_TYPE_MASTER).intValue() : 0;
        logStatList.add(LogStatVO.builder()
                .operatorType(GlobalConsts.OPERATE_USER_TYPE_MASTER)
                .operatorTypeName("工程师")
                .operateCount(masterOptCount).build());

        // 用户
        int userOptCount = optCountMap.containsKey(GlobalConsts.OPERATE_USER_TYPE_USER) ? optCountMap.get(GlobalConsts.OPERATE_USER_TYPE_USER).intValue() : 0;
        logStatList.add(LogStatVO.builder()
                .operatorType(GlobalConsts.OPERATE_USER_TYPE_USER)
                .operatorTypeName(GlobalConsts.getOperatorTypeName(GlobalConsts.OPERATE_USER_TYPE_USER))
                .operateCount(userOptCount).build());

        // 系统
        int sysOptCount = optCountMap.containsKey(GlobalConsts.OPERATE_USER_TYPE_SYSTEM) ? optCountMap.get(GlobalConsts.OPERATE_USER_TYPE_SYSTEM).intValue() : 0;
        logStatList.add(LogStatVO.builder()
                .operatorType(GlobalConsts.OPERATE_USER_TYPE_SYSTEM)
                .operatorTypeName(GlobalConsts.getOperatorTypeName(GlobalConsts.OPERATE_USER_TYPE_SYSTEM))
                .operateCount(sysOptCount).build());

        return logStatList;
    }

    /**
     * 获取领取用户名称
     * @param orderWork
     * @param orderWarranty
     * @return
     */
    private String getGrantUserName(OrderWork orderWork, OrderWarranty orderWarranty) {

        Long warrantyUserId = orderWarranty.getUserId();
        if (NumberUtil.isNullOrZero(warrantyUserId)) {
            return GlobalConsts.SPLITER_EMPTY;
        }

        Long visitUserId = orderWork.getVisitUserId();
        if (Objects.equals(visitUserId, warrantyUserId)) {
            return "上门扫码用户";
        }

        Long customerId = orderWork.getCustomerId();
        if (Objects.equals(customerId, warrantyUserId)) {
            return "微信支付用户领取";
        }

        Long userId = orderWork.getUserId();
        if (Objects.equals(userId, warrantyUserId)) {
            return "下单用户领取";
        }

        return GlobalConsts.SPLITER_EMPTY;
    }

    @Override
    public ZsOrderWorkVO findOrderWorkByOuterId(String outerId, Integer channelId) {
        if (StringUtils.isBlank(outerId)) {
            return null;
        }

        OrderWorkQuery query = new OrderWorkQuery();
        query.setOuterId(outerId);

        if (channelId != null) {
            List<Integer> channelIdList = new LinkedList<>();
            channelIdList.add(channelId);
            query.setChannelIdList(channelIdList);
        }

        List<ZsOrderWorkVO> zsOrderWorkVOList = listPageOrderWorkByQueryNoRecord(query);
        if (CollectionUtils.isEmpty(zsOrderWorkVOList)) {
            return null;
        }
        return zsOrderWorkVOList.get(0);
    }

    @Override
    public ZsOrderWorkVO findOrderWorkByOuterIdAndChannelIds(String outerId, List<Integer> channelIdList) {
        if (StringUtils.isBlank(outerId)) {
            return null;
        }

        OrderWorkQuery query = new OrderWorkQuery();
        query.setOuterId(outerId);

        if (!CollectionUtils.isEmpty(channelIdList)) {
            query.setChannelIdList(channelIdList);
        }

        List<ZsOrderWorkVO> zsOrderWorkVOList = listPageOrderWorkByQueryNoRecord(query);
        if (CollectionUtils.isEmpty(zsOrderWorkVOList)) {
            return null;
        }
        return zsOrderWorkVOList.get(0);
    }

    @Override
    public EsOrderWork findEsOrderWorkByOuterId(String outerId, Integer channelId) {
        OrderWorkQuery query = new OrderWorkQuery();
        query.setOuterId(outerId);

        if (channelId != null) {
            List<Integer> channelIdList = new LinkedList<>();
            channelIdList.add(channelId);
            query.setChannelIdList(channelIdList);
        }

        List<EsOrderWork> esOrderWorks = orderWorkListBService.listPageOrderWorkByQuery(query);
        if (CollectionUtils.isEmpty(esOrderWorks)) {
            return null;
        }

        return esOrderWorks.get(0);
    }

    @Override
    public EsOrderWork findEsOrderWorkByOuterIdAndChannelIds(String outerId, List<Integer> channelIdList) {
        OrderWorkQuery query = new OrderWorkQuery();
        query.setOuterId(outerId);

        if (!CollectionUtils.isEmpty(channelIdList)) {
            query.setChannelIdList(channelIdList);
        }

        List<EsOrderWork> esOrderWorks = orderWorkListBService.listPageOrderWorkByQuery(query);
        if (CollectionUtils.isEmpty(esOrderWorks)) {
            return null;
        }

        return esOrderWorks.get(0);
    }

    @Override
    public Map<String, Object> findDynamicOrderWorkInfo(com.zmn.oms.common.dio.normal.order.OrderWorkQuery query) throws OmsBaseException {
        Map<String, Object> map = Maps.newHashMap();

        OrderWork orderWork = null;
        // 查询orderWork表
        //String orderWorkQuery = this.getTableFields(query.getFieldList(), OrderWork.class);
        String orderWorkQuery = Arrays.stream(OrderWork.class.getDeclaredFields()).map(Field::getName)
                .filter(str -> query.getFieldList().contains(str)).collect(Collectors.joining(","));
        logger.info("[{}]查询orderWork语句：[{}]", query.getOrderId(), orderWorkQuery);
        if (StringUtil.isNotBlank(orderWorkQuery)) {
            orderWorkQuery = this.humpToUnderline(orderWorkQuery);
            orderWork = orderWorkService.findDynamicOrderWorkByKey(orderWorkQuery, query.getOrderId(), query.getWorkId());
            if (Objects.isNull(orderWork)) {
                return map;
            }
            try {
                // 转换map
                this.objectToMap(map, query.getFieldList(), orderWork);
            } catch (IllegalAccessException e) {
                throw new OmsBaseException("对象转换异常");
            }
        }

        // 查询orderDetail表
        //String orderDetailQuery = this.getTableFields(query.getFieldList(), OrderDetail.class);
        String orderDetailQuery = Arrays.stream(OrderDetail.class.getDeclaredFields()).map(Field::getName)
                .filter(str -> query.getFieldList().contains(str)).collect(Collectors.joining(","));
        logger.info("[{}]查询orderDetail语句：[{}]", query.getOrderId(), orderDetailQuery);
        if (StringUtil.isNotBlank(orderDetailQuery)) {
            orderDetailQuery = this.humpToUnderline(orderDetailQuery);
            OrderDetail orderDetail = orderDetailService.findDynamicOrderDetailByKey(orderDetailQuery, query.getOrderId());
            if (Objects.isNull(orderDetail)) {
                return map;
            }
            try {
                // 转换map
                this.objectToMap(map, query.getFieldList(), orderDetail);
            } catch (IllegalAccessException e) {
                throw new OmsBaseException("对象转换异常");
            }
        }

        // 获取一对多查询条件，key为哪个表，value为sql语句
        Map<String, Set<String>> tableMap = new HashMap<>();
        for (String str : query.getFieldList()) {
            if (!str.contains(".")) {
                continue;
            }

            String[] strArray = str.split("\\.");
            Set<String> value = tableMap.get(strArray[0]);
            if (CollectionUtil.isNullOrEmpty(value)) {
                tableMap.put(strArray[0], Sets.newHashSet(strArray[1]));
            } else {
                value.add(strArray[1]);
            }
        }

        if (CollectionUtil.isNotNullOrEmpty(tableMap)) {

            // 服务项数据
            if (tableMap.keySet().contains("serviceItemList")) {
                Set<String> serviceItemFieldList = tableMap.get("serviceItemList");
                /*String orderServiceItemQuery = Arrays.stream(OrderServiceItem.class.getDeclaredFields())
                        .map(Field::getName).filter(str -> serviceItemFieldList.contains(str))
                        .collect(Collectors.joining(","));*/
                //logger.info("[{}]查询orderServiceItem语句：[{}]", query.getOrderId(), orderServiceItemQuery);
                //if (StringUtil.isNotBlank(orderServiceItemQuery)) {
                    List<OrderServiceItem> serviceItemList = orderServiceItemService.listByOrderId(query.getOrderId());
                    if (CollectionUtil.isNotNullOrEmpty(serviceItemList)) {
                        List<Map<String, Object>> list = Lists.newArrayListWithCapacity(serviceItemList.size());
                        serviceItemList.forEach(item -> {
                            Map<String, Object> itemMap = Maps.newHashMap();
                            try {
                                // 转换map
                                this.objectToMap(itemMap, serviceItemFieldList, item);
                            } catch (IllegalAccessException e) {
                                logger.error("[{}]服务项对象转换异常", query.getOrderId());
                            }
                            list.add(itemMap);
                        });
                        map.put("serviceItemList", list);
                    }
                //}
            }

            // 工程师数据，工程师字段少，直接全查
            if (tableMap.keySet().contains("masterList")) {
                Set<String> masterFieldList = tableMap.get("masterList");
                //String orderMasterQuery = Arrays.stream(OrderMaster.class.getClass().getDeclaredFields())
                        //.map(Field::getName).filter(str -> masterFieldList.contains(str))
                        //.collect(Collectors.joining(","));
                //logger.info("[{}]查询orderMaster语句：[{}]", query.getOrderId(), orderMasterQuery);
                //if (StringUtil.isNotBlank(orderMasterQuery)) {
                    List<OrderMaster> orderMasterList = orderMasterService.listMasterByWorkId(query.getOrderId(), query.getWorkId());
                    if (CollectionUtil.isNotNullOrEmpty(orderMasterList) && orderMasterList.size() > 1) {
                        List<Map<String, Object>> list = Lists.newArrayListWithCapacity(orderMasterList.size());
                        OrderWork finalOrderWork = orderWork;
                        orderMasterList.forEach(item -> {
                            // 如果是主工程师直接跳出循环
                            if (Objects.equals(item.getMasterId(), finalOrderWork.getMasterId())) {
                                return;
                            }
                            Map<String, Object> itemMap = Maps.newHashMap();
                            try {
                                // 转换map
                                this.objectToMap(itemMap, masterFieldList, item);
                            } catch (IllegalAccessException e) {
                                logger.error("[{}]工程师对象转换异常", query.getOrderId());
                            }
                            list.add(itemMap);
                        });
                        map.put("masterList", list);
                    }
                //}
            }
        }

        // 查询orderMaster表
        /*if (query.getFieldList().contains("masterPhone") && query.getFieldList().contains("masterId")) {
            List<OrderMaster> orderMasterList = orderMasterService.listMasterByWorkId(query.getOrderId(), query.getWorkId());
            if (CollectionUtil.isNotNullOrEmpty(orderMasterList)) {
                Optional<OrderMaster> orderMasterOptional = orderMasterList.stream()
                        .filter(e -> Objects.equals(e.getMasterId(), map.get("masterId"))).findFirst();
                if (orderMasterOptional.isPresent()) {
                    map.put("masterPhone", orderMasterOptional.get().getMasterPhone());
                }
            }
        }*/
        return map;
    }

    /**
     * 驼峰转下划线
     * @param str
     * @return
     */
    private String humpToUnderline(String str) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            if (Character.isUpperCase(str.charAt(i))) {
                sb.append("_").append(String.valueOf(str.charAt(i)).toLowerCase());
                continue;
            }
            sb.append(str.charAt(i));
        }
        return sb.toString();
    }

    /**
     * 对象转map
     * @param map
     * @param list
     * @param object
     * @throws IllegalAccessException
     */
    private void objectToMap(Map<String, Object> map, Set<String> list, Object object) throws IllegalAccessException {
        Class<?> clazz = object.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            if (!list.contains(field.getName())) {
                continue;
            }
            field.setAccessible(true);
            map.put(field.getName(), field.get(object));
        }
    }

    /**
     * 获取查询sql
     * @return
     */
    /*private String getTableFields(Set<String> list, Object object) {
        String query = Arrays.stream(object.getClass().getDeclaredFields()).map(Field::getName).filter(str -> list.contains(str)).collect(Collectors.joining(","));
        *//*StringJoiner sj = new StringJoiner(",");
        List<String> fieldList = Arrays.stream(clazz.getDeclaredFields()).map(Field::getName).collect(Collectors.toList());
        fieldList.forEach(s -> {
            if (list.contains(s)) {
                sj.add(s);
            }
        });*//*
        return query;
    }*/

    @StaffOperateRecord(staffId = "{{#query.staffId}}",
            event = EventEnum.WORK_ORDER_QUERY,
            mapping = {
            @RecordField(field = RecordFieldEnum.STAFF_IP, value = "{{#query.ip}}"),
            @RecordField(field = RecordFieldEnum.PLAT, value = "{{#query.platWork}}")
    })
    @Override
    public List<ZsOrderWorkVO> listPageOrderWorkByQuery(OrderWorkQuery query) {
        return listPageOrderWorkByQueryNoRecord(query);
    }


    @Override
    public List<ZsOrderWorkVO> listPageOrderWorkByQueryNoRecord(OrderWorkQuery query) {

        // 处理查询条件
        this.processWorkQuery(query);

        List<EsOrderWork> esOrderWorks = orderWorkListBService.listPageOrderWorkByQuery(query);
        if (CollectionUtils.isEmpty(esOrderWorks)) {
            return Lists.newArrayList();
        }

        // 解密电话和地址
        orderEncryptService.batchDecryptEsOrderWork(esOrderWorks, EncryptFieldTypeEnum.USER_TELPHONE, EncryptFieldTypeEnum.USER_ADDRESS);

        // 转 vo
        List<ZsOrderWorkVO> voList = Lists.newArrayList();

        // 检查是否要查询警告标识
        Map<Long, ZsWarningVO> finalWarningMap = null;
        Integer queryWarning = query.getQueryWarning();
        if (Objects.equals(queryWarning, GlobalConsts.YES)) {
            finalWarningMap = listWarningByWorkList(esOrderWorks);
        }

        // 标记配置
//        List<ConfOrderTag> confOrderTagList = confOrderTagService.listConfByQuery(ConfOrderTagQuery.builder().build());
//        Map<Integer, ConfOrderTag> confOrderTagMap = confOrderTagList.stream().collect(Collectors.toMap(ConfOrderTag::getId, item -> item, (k1, k2) -> k1));

        for (EsOrderWork esOrderWork : esOrderWorks) {
            ZsOrderWorkVO vo = new ZsOrderWorkVO();
            BeanUtils.copyProperties(esOrderWork, vo);
            List<EsOrderWorkProduct> productList = esOrderWork.getProductList();
            if (CollectionUtil.isNotNullOrEmpty(productList)) {
                EsOrderWorkProduct esOrderWorkProduct = productList.get(0);
                String productName = StringUtil.isBlank(esOrderWorkProduct.getProductName()) ? esOrderWorkProduct.getShowProductName() : esOrderWorkProduct.getProductName();
//            String productName = StringUtils.defaultString(esOrderWorkProduct.getProductName(), esOrderWorkProduct.getShowProductName());
                vo.setProductInfo(String.format("%s-%s*%s", StringUtils.defaultString(esOrderWorkProduct.getBrandName()), productName, esOrderWorkProduct.getNumber()));
            }
            vo.setWorkId(esOrderWork.getId());
            vo.setBizType(esOrderWork.getBizType());
            vo.setPrepayStatusName(PayConsts.getPayStatusName(esOrderWork.getPrepayStatus()));
            vo.setDepositStatusName(PayConsts.getPayStatusName(esOrderWork.getDepositStatus()));
            EsOrderWorkContact concat = esOrderWork.getContact();
            if (Objects.nonNull(concat)) {
                vo.setUsername(concat.getContactName());
                // vo.setUserAddress(concat.getAddress());
                if (query.getIsSensitiveAddr()) {
                    vo.setUserAddress("****");
                } else {
                    vo.setUserAddress(concat.getAddress());
                }
                vo.setUserStreet(concat.getStreet());
                vo.setGender(concat.getGender());
                if (query.getIsSensitiveAddr()) {
                    vo.setUserPhone(MobileUtil.formatHideTel(concat.getPhone()[0]));
                } else {
                    vo.setUserPhone(concat.getPhone()[0]);
                }
            }
            if (finalWarningMap != null) {
                vo.setWarningVO(finalWarningMap.get(esOrderWork.getId()));
            }
            // 多次上门
            if (CollectionUtil.isNotNullOrEmpty(esOrderWork.getOrderVisitList())) {
                if (Objects.equals(esOrderWork.getStatus(), OrderStatusConsts.WORK_STATUS_VISIT)) {
                    vo.setMultipleVisitStatusName(esOrderWork.getOrderVisitList().get(esOrderWork.getOrderVisitList().size() - 1).getVisitStatusName());
                }
            }
            voList.add(vo);
        }
        return voList;
    }

    private void setTagVoList(ZsOrderWorkVO vo, ZsWarningVO warningVO, Map<Integer, ConfOrderTag> confOrderTagMap){
        List<OrderTagVO> orderTagVoList = Lists.newArrayListWithExpectedSize(50);

        // 重点渠道
        if (warningVO.getIsEmphasisChannel()) {
            ConfOrderTag confOrderTag = confOrderTagMap.get(OrderTagConsts.TAG_ID_IMPORTANT_CHANNEL);
            if (Objects.nonNull(confOrderTag)) {
                orderTagVoList.add(OrderTagVO.builder()
                        .tagId(OrderTagConsts.TAG_ID_IMPORTANT_CHANNEL)
                        .tagName(confOrderTag.getTagName())
                        .tagShortName(confOrderTag.getTagShortName())
                        .bgColor(confOrderTag.getColor())
                        .display(confOrderTag.getDisplay()).build());
            }
        }


    }

    @Override
    public Integer countOrderWorkByQuery(OrderWorkQuery query) {

        // 处理查询条件
        this.processWorkQuery(query);

        // 如果有城市查询条件，忽略城市权限
        if (!CollectionUtils.isEmpty(query.getCountyIdList())) {
            query.setPermitCity(GlobalConsts.NO);
        }
        // 有渠道查询条件，忽略渠道权限
        if (!CollectionUtils.isEmpty(query.getChannelIdList())) {
            query.setPermitChannel(GlobalConsts.NO);
        }

        return orderWorkListBService.countOrderWorkByQuery(query);
    }

    /**
     * 查询条件处理
     *
     * @param query
     */
    @Override
    public void processWorkQuery(OrderWorkQuery query) {

        // 如果vvip等于1，则把vip设为2，es查询不等于2的所有工单。
        /*if (Objects.equals(GlobalConsts.NO, query.getVvip())) {
            query.setVvip(null);
            query.setVip(GlobalConsts.YES);
        }*/

        // 退款时间查，只查询退款单的
        if (StringUtils.isNotBlank(query.getRefundAmountTime())) {
            query.setWorkType(Arrays.asList(OrderConsts.ORDER_TYPE_REFUND));
        }

        // 查询预约失败
        if (Objects.equals(GlobalConsts.YES, query.getIsDutyFail())) {
            query.setDutyStatusList(Lists.newArrayList(OrderDutyConsts.DUTY_STATUS_FAIL));
            query.setDutyFailCode(query.getDutyFailReasonCode());
        }
        // 查询挂起
        if (Objects.equals(GlobalConsts.YES, query.getIsDutySuspend())) {
            query.setDutyStatusList(Lists.newArrayList(OrderDutyConsts.DUTY_STATUS_SUSPEND));
            query.setDutyFailCode(query.getDutySuspendReasonCode());
        }

        // 只有选择天猫勤鸽这一个渠道时，才允许使用"签到状态"这个查询条件
        List<Integer> channelIdList = query.getChannelIdList();
        boolean isOnlyTmallQingeChannel = CollectionUtils.isNotEmpty(channelIdList) &&
                channelIdList.size() == 1 && channelIdList.contains(OrderConsts.CHANNEL_ID_TMALL_WYG);
        if (!isOnlyTmallQingeChannel) {
            query.setSignInStatus(null);
        }

        // 处理回溯天数
        if (Objects.equals(query.getPermit(), GlobalConsts.YES)) {
            ResponseDTO<List<RoleDRO>> listResponseDTO = roleListRemoteService.listByIds(query.getRoleIds());
            List<RoleDRO> roleDROList = listResponseDTO.getData();
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(roleDROList)) {
                RoleDRO roleDRO = roleDROList.stream().max((item1, item2) -> {
                    if (Objects.isNull(item1.getDayLimit())) {
                        return -1;
                    }
                    if (Objects.isNull(item2.getDayLimit())) {
                        return 1;
                    }
                    if (item1.getDayLimit() > item2.getDayLimit()) {
                        return 1;
                    } else {
                        return -1;
                    }
                }).get();

                if (Objects.nonNull(roleDRO.getDayLimit())) {
                    Date minDate = DateUtil.addDays(new Date(), -1 * roleDRO.getDayLimit());
                    query.setInputTime(String.format("%s,", DateUtil.dateFormatToString(minDate, DateUtil.FORMAT_DEFAULT)));
                }
            }
        }

        // 改约改派
        if (!Objects.equals(query.getModifyType(), GlobalConsts.NONE)) {
            // 改派
            if (Objects.equals(query.getModifyType(), GlobalConsts.YES)) {
                query.setDistributeModifyCountRange("1");
            }
            // 改约
            if (Objects.equals(query.getModifyType(), GlobalConsts.NO)) {
                query.setDutyTimeModifyCountRange("1");
            }
        }

        // 服务商结算列表查询 订单的完成时间大于等于2020-11-07
        if (Objects.equals(query.getSpStatement(), GlobalConsts.YES) && Objects.isNull(query.getSpStatementTime())) {
            query.setCompleteTime(String.format("%s,%s", "2020-11-07 00:00:00", DateUtil.getNowFormatted()));
        }

        // 用户层级处理
        if (Objects.nonNull(query.getUserLevel())) {
            // 999代表要客
            if (Objects.equals(query.getUserLevel(), 999)) {
                query.setVvip(GlobalConsts.YES);
            } else {
                query.setTagType(OrderTagConsts.ORDER_TAG_USER_SYSTEM);
                query.setTagId(OrderTagConsts.TAG_ID_HIGH_VALUE_USER);
            }
        }

        // 抢单类型处理
        if (Objects.nonNull(query.getGrabType()) && !Objects.equals(query.getGrabType(), GlobalConsts.YES)) {
            query.setGrabType(null);
            query.setNonGrabType(GlobalConsts.YES);
        }

        // 退款审批处理
        if (CollectionUtil.isNotNullOrEmpty(query.getRefundWorkReviewStatusList())) {
            query.setSingleWorkType(OrderConsts.ORDER_TYPE_REFUND);
        }

        // 赔偿审批处理
        if (CollectionUtil.isNotNullOrEmpty(query.getCompensateWorkReviewStatusList())) {
            query.setSingleWorkType(OrderConsts.ORDER_TYPE_COMPENSATE);
        }

        // 待收单查询-工单分润未设置时，只查询多工程师
        if (Objects.equals(query.getShareRate(), com.zmn.consts.GlobalConsts.NO)) {
            query.setMultiMaster(com.zmn.consts.GlobalConsts.YES);
        }

        // 从工程师查询
        if (Objects.nonNull(query.getMultiMasterId())) {
            query.setMultiMaster(com.zmn.consts.GlobalConsts.YES);
            query.setMasterType(OrderConsts.ORDER_MASTER_TYPE_SLAVE);
            query.setNonMasterId(query.getMultiMasterId());
        }

        // 价格类型查询处理
        if (Objects.equals(query.getServItemType(), OrderConsts.SERVICE_ITEM_TYPE_QUOTATION_THREE)) {
            query.setFinalPrice(GlobalConsts.NO);
        }
        if (Objects.equals(query.getServItemType(), OrderConsts.SERVICE_ITEM_TYPE_FINAL_PRICE)) {
            query.setServItemType(OrderConsts.SERVICE_ITEM_TYPE_QUOTATION_THREE);
            query.setFinalPrice(GlobalConsts.YES);
        }
    }

    /**
     * 处理工单
     * @param partList
     * @return
     */
    private List<ZsOrderWorkDetailPartStatVO> processOrderDetailPart(List<OrderPart> partList) {
        Map<Integer, List<OrderPart>> deliverListMap = partList.stream()
                .collect(Collectors.groupingBy(OrderPart::getMasterId));
        List<ZsOrderWorkDetailPartStatVO> partVOList = Lists.newArrayList();
        deliverListMap.forEach((k, orderPartList) -> {

            List<ZsOrderPartVO> orderPartVOList = orderPartList.stream()
                    .map(orderPart -> {
                        ZsOrderPartVO orderPartVO = BeanMapper.map(orderPart, ZsOrderPartVO.class);
                        orderPartVO.setReimburseStatusName(OrderConsts.getOrderPartReimburseStatusName(orderPartVO.getReimburseStatus()));
                        return orderPartVO;
                    })
                    .collect(Collectors.toList());

            int amount = orderPartList.stream().flatMapToInt(e -> IntStream.of(MathUtil.amountMultiplyNumber(e.getPrice(),
                    e.getNumber()))).sum();
            int declarePrice = orderPartList.stream().flatMapToInt(e -> IntStream.of(MathUtil.amountMultiplyNumber(
                    Optional.ofNullable(e.getDeclarePrice()).orElse(GlobalConsts.NONE), e.getNumber()))).sum();
            int costAmount = orderPartList.stream().flatMapToInt(e -> IntStream.of(MathUtil.amountMultiplyNumber(
                    Optional.ofNullable(e.getCostPrice()).orElse(GlobalConsts.NONE), e.getNumber()))).sum();
            int purchasePrice = orderPartList.stream().flatMapToInt(e -> IntStream.of(MathUtil.amountMultiplyNumber(
                    Optional.ofNullable(e.getPurchasePrice()).orElse(GlobalConsts.NONE), e.getNumber()))).sum();
            ZsOrderWorkDetailPartStatVO detailPartStatVO = new ZsOrderWorkDetailPartStatVO();
            detailPartStatVO.setAmount(amount);
            detailPartStatVO.setCostAmount(costAmount);
            detailPartStatVO.setDeclarePrice(declarePrice);
            detailPartStatVO.setPurchasePrice(purchasePrice);
            detailPartStatVO.setMasterName(orderPartList.get(0).getMasterName());
            detailPartStatVO.setPartList(orderPartVOList);
            partVOList.add(detailPartStatVO);
        });
        return partVOList;
    }

    /**
     * 查询警告
     * @param orderWork
     * @return
     */
    private ZsWarningVO findWarningByWork(OrderWork orderWork, OrderExtend orderExtend, OrderDetail orderDetail) {

        Integer channelId = orderWork.getChannelId();
        Long workId = orderWork.getWorkId();
        Long userId = orderWork.getUserId();

        // 重点渠道
        Map<Integer, Integer> channelMap = listChannelPlatformTypeMap(Lists.newArrayList(channelId));

        // 投诉异常数据
        Map<Long, TrackAbnormalWarningVO> complainMap = listTrackComplainMap(Lists.newArrayList(workId));

        // 要客标识
//        Map<Long, Boolean> userVipMap = listUserVipMap(Lists.newArrayList(userId));

        // 预警超时
        Map<Long, TimeoutStatusBO> timeoutStatusBOMap = listTimeoutMap(Lists.newArrayList(workId));

        // 标准收费单
        ZsWarningVO zsWarningVO = new ZsWarningVO();

        // 未完成进行中显示重点渠道
        boolean channelA = Objects.equals(orderWork.getResultStatus(), OrderStatusConsts.WORK_RESULT_DOING);
        boolean channelB = orderWork.getStatus() < OrderStatusConsts.ORDER_STATUS_COMPLETE;
        if (channelA && channelB && channelMap != null && channelMap.containsKey(channelId)) {
            Integer type = channelMap.get(channelId);
            zsWarningVO.setIsEmphasisChannel(Objects.equals(type, 3));
        }

        if (complainMap != null && complainMap.containsKey(workId)) {
            TrackAbnormalWarningVO complainLevelDRO = complainMap.get(workId);
            zsWarningVO.setComplainLevel(complainLevelDRO.getLevel());
            zsWarningVO.setHasAbnormal(complainLevelDRO.getAbnormalStatus());
            zsWarningVO.setComplainLevelName(complainLevelDRO.getLevelName());
        }

//        if (userVipMap != null && userVipMap.containsKey(userId)) {
        zsWarningVO.setIsVip(Objects.equals(orderDetail.getVvip(), GlobalConsts.YES));
//        }

        if (timeoutStatusBOMap != null && timeoutStatusBOMap.containsKey(workId)) {
            TimeoutStatusBO timeoutStatusBO = timeoutStatusBOMap.get(workId);
            zsWarningVO.setHasWarning(timeoutStatusBO.getHasWarning());
            zsWarningVO.setHasTimeout(timeoutStatusBO.getHasTimeout());
        }

        // 一口价
        if (Objects.equals(orderWork.getFinalPrice(), GlobalConsts.YES)) {
            zsWarningVO.setIsFinalPrice(true);
        }

        // 返修要求
        if (Objects.equals(orderWork.getAutoDistribute(), GlobalConsts.NO)) {
            zsWarningVO.setIsReworkDemand(true);
        }

        //  计价器工单预警
        if (Objects.equals(OrderConsts.SERVICE_ITEM_TYPE_FAULT, orderWork.getServItemType())) {
            zsWarningVO.setIsQuotation(true);
        }
        //  提前付工单预警
        if (Objects.equals(OrderConsts.SERVICE_ITEM_TYPE_ADVANCE_PAY, orderWork.getServItemType())) {
            zsWarningVO.setIsAdvancePay(true);
        }
        //  计价器3.0工单预警
        if (servItemBService.isQuotationThreeType(orderWork.getServItemType(), orderWork.getFinalPrice())) {
            zsWarningVO.setIsQuotationThree(true);
        }

        // 挂起订单预警(当工单有挂起原因，并且无：预约时间，并且未完成&未取消，则显示警示)
        List<Integer> supportResultStatusList = Lists.newArrayList(OrderStatusConsts.WORK_RESULT_DOING);
        List<Integer> supportStatus = Lists.newArrayList(
                OrderStatusConsts.WORK_STATUS_INPUT,
                OrderStatusConsts.WORK_STATUS_CONFIRM,
                OrderStatusConsts.WORK_STATUS_ASSIGN,
                OrderStatusConsts.WORK_STATUS_DISTRIBUTE,
                OrderStatusConsts.WORK_STATUS_TAKE,
                OrderStatusConsts.WORK_STATUS_VISIT);
        boolean resultstatus = supportStatus.contains(orderWork.getStatus());
        boolean resultStatusSupport = supportResultStatusList.contains(orderWork.getResultStatus());
        boolean support = resultstatus && resultStatusSupport;
        boolean status = orderWork.getDutyTime() == null && support;
        if (status) {
            if (Objects.equals(orderWork.getDutyStatus(), OrderDutyConsts.DUTY_STATUS_SUSPEND)) {
                zsWarningVO.setIsSuspend(true);
            } else if (Objects.equals(orderWork.getDutyStatus(), OrderDutyConsts.DUTY_STATUS_FAIL)) {
                zsWarningVO.setIsDutyFailed(true);
            }
        }

        try {
            // 计价器-有效使用
            if (orderWork.getStatus() >= OrderStatusConsts.WORK_STATUS_CHECKOUT && Objects.equals(orderWork.getServItemType(), OrderConsts.SERVICE_ITEM_TYPE_FAULT)) {
                ResponseDTO<OrderBehaviorDRO> orderBehaviorresponseDTO = orderBehaviorListRemoteService.getByWorkId(orderWork.getWorkId());
                logger.info("orderBehaviorListRemoteService#getByWorkId返回=>[{}]", JSON.toJSONString(orderBehaviorresponseDTO));
                if (orderBehaviorresponseDTO.isSuccess() && Objects.nonNull(orderBehaviorresponseDTO.getData())) {
                    OrderBehaviorDRO orderBehaviorDRO = orderBehaviorresponseDTO.getData();
                    if (orderBehaviorDRO != null && NumberUtil.isNotNullOrZero(orderBehaviorDRO.getTariff())) {
                        zsWarningVO.setIsQuotationValid(Objects.equals(orderBehaviorDRO.getTariff(), GlobalConsts.YES));
                    }
                }
            }
        } catch (Exception ex) {
            logger.warn("工单[{}] 查询计价器是否有效失败：{}", orderWork.getOrderId(), ex);
        }


        // 三日无忧退
        if (Objects.nonNull(orderExtend)) {
            zsWarningVO.setIsAllowRefund(Objects.equals(orderExtend.getAllowRefund(), GlobalConsts.YES));
        }


        // 测试单
        /*List<OrderRemarkDetail> orderRemarkDetails = orderRemarkDetailService.listOrderRemarkDetailByOrderIdList(Lists.newArrayList(orderWork.getOrderId()));
        boolean isCancelForTest = orderRemarkDetails.stream().anyMatch(detail -> {
            return Objects.equals(detail.getType(), OrderConsts.ORDER_REMARK_TYPE_CANCEL) && Objects.equals(detail.getMapId(), OrderConsts.CANCEL_TEST_ID);
        });*/
        zsWarningVO.setIsTest(Objects.equals(orderWork.getTest(), com.zmn.consts.GlobalConsts.YES));

        if (Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_REFUND)) {
            // 退款审核标识
            OmsOrderReview refundReview = orderReviewService.getOmsOrderReviewByOrderIdAndWorkIdAndType(orderWork.getOrderId(), orderWork.getWorkId(), OrderConsts.OMS_ORDER_REVIEW_REFUND);
            zsWarningVO.setIsRefundWaitReview(Objects.nonNull(refundReview) && Objects.equals(refundReview.getReviewStatus(), OrderConsts.OMS_ORDER_REVIEW_STATUS_CHECK));

            // 打款标识
            if (Objects.isNull(refundReview)) {
                zsWarningVO.setIsRemit(Objects.equals(orderWork.getPayStatus(),PayConsts.REFUND_STATUS_ING));
            }else {
                zsWarningVO.setIsRemit(!Objects.equals(refundReview.getReviewStatus(), OrderConsts.OMS_ORDER_REVIEW_STATUS_CHECK) && Objects.equals(orderWork.getPayStatus(), PayConsts.REFUND_STATUS_ING));
            }
        }

        // 订单标签处理
        this.processOrderTag(orderWork, zsWarningVO);

        // 增值单
        this.processVasMember(orderWork, zsWarningVO);

        return zsWarningVO;
    }

    /**
     * 增值单查询
     * @param orderWork
     * @param zsWarningVO
     */
    private void processVasMember(OrderWork orderWork, ZsWarningVO zsWarningVO){
        if (!Objects.equals(orderWork.getSourceType(), OrderConsts.ORDER_SOURCE_TYPE_MEMBER)) {
            return;
        }
        // 兼容查询增值单
        boolean isMember = false;
        if (CollectionUtil.isNotNullOrEmpty(zsWarningVO.getTagList())) {
            isMember = zsWarningVO.getTagList().stream().anyMatch(item -> Objects.equals(item.getTagId(), OrderTagConsts.TAG_ID_WORK_VAS_MEMBER_LEVEL_1) ||
                    Objects.equals(item.getTagId(), OrderTagConsts.TAG_ID_WORK_VAS_MEMBER_LEVEL_2));
        }
        // tag 中已存在，不查询
        if(isMember){
            return;
        }

        // 兼容老数据，查询增值服务
        // 查询通行证下所有的UserId
        try {
            ResponseDTO<UserDetailDRO> userDetailDROResponseDTO = userListRemoteService.getUserDetailById(orderWork.getUserId(), false);
            if (userDetailDROResponseDTO.getData() == null) {
                return;
            }
            if (NumberUtil.isNullOrZero(userDetailDROResponseDTO.getData().getPassId())) {
                return;
            }
            logger.info("#oms#工单={},是否是会员工单，入参={}", orderWork.getOrderId(), userDetailDROResponseDTO.getData().getPassId());
            ResponseDTO<MemberDRO> memberDROResponseDTO = memberListRemoteService.getMemberById(userDetailDROResponseDTO.getData().getPassId());
            logger.info("#oms#工单={},是否是会员工单，出参={}", orderWork.getOrderId(), JSON.toJSONString(memberDROResponseDTO));
            MemberDRO memberDRO = memberDROResponseDTO.getData();
            if (memberDRO == null || !Objects.equals(memberDRO.getStatus(), GlobalConsts.YES)) {
                return;
            }
            zsWarningVO.setIsNineDollarsNine(true);
        } catch (Exception ex) {
            logger.warn("查询用户信息失败，订单：[{}]", orderWork.getOrderId());
        }
    }

    /**
     * 订单标签处理
     * @param orderWork
     * @param zsWarningVO
     */
    private void processOrderTag(OrderWork orderWork, ZsWarningVO zsWarningVO) {
        List<OrderTag> orderTagList = orderTagService.listOrderTagByOrderIdList(Lists.newArrayList(orderWork.getOrderId()));
        if (CollectionUtil.isNullOrEmpty(orderTagList)) {
            return;
        }

        // 订单标志
        List<ConfOrderTag> confOrderTagList = confOrderTagService.listByQuery(ConfOrderTagQuery.builder().build());
        Map<Integer, ConfOrderTag> confOrderTagMap = confOrderTagList.stream().collect(Collectors.toMap(ConfOrderTag::getId, item -> item, (k1, k2) -> k1));

        List<OrderTagVO> tagVOList = orderTagList.stream()
                .filter(item -> Objects.equals(item.getWorkId(), orderWork.getWorkId()) && confOrderTagMap.containsKey(item.getTagId()))
                .filter(item -> !Objects.equals(item.getTagId(), OrderTagConsts.TAG_ID_WORK_TEST))
                .map(orderTag -> {
                    if (Objects.equals(orderTag.getTagId(), OrderTagConsts.USER_TAG_ID_HIGH_VALUE)) {
                        orderTag.setTagId(OrderTagConsts.TAG_ID_HIGH_VALUE_USER);
                    }
                    ConfOrderTag confOrderTag = confOrderTagMap.get(orderTag.getTagId());
                    return OrderTagVO.builder()
                            .tagId(orderTag.getTagId())
                            .tagName(confOrderTag.getTagName())
                            .tagShortName(confOrderTag.getTagShortName())
                            .bgColor(confOrderTag.getColor())
                            .display(confOrderTag.getDisplay()).build();
                }).collect(Collectors.toList());
        zsWarningVO.setTagList(tagVOList);
    }

    /**
     * 查询警告
     * @param esOrderWorks
     * @return
     */
    @Override
    public Map<Long, ZsWarningVO> listWarningByWorkList(List<EsOrderWork> esOrderWorks) {

        Set<Integer> channelIdSet = esOrderWorks.stream().map(EsOrderWork::getChannelId).collect(Collectors.toSet());
        Set<Long> workIdSet = esOrderWorks.stream().map(EsOrderWork::getId).collect(Collectors.toSet());

        // 重点渠道
        Map<Integer, Integer> channelMap = listChannelPlatformTypeMap(Lists.newArrayList(channelIdSet));

        // 投诉异常数据
        Map<Long, TrackAbnormalWarningVO> complainMap = listTrackComplainMap(Lists.newArrayList(workIdSet));

        // 订单标志
        List<ConfOrderTag> confOrderTagList = confOrderTagService.listByQuery(ConfOrderTagQuery.builder().build());
        Map<Integer, ConfOrderTag> confOrderTagMap = confOrderTagList.stream().collect(Collectors.toMap(ConfOrderTag::getId, item -> item, (k1, k2) -> k1));

        // 超时预警
        Map<Long, TimeoutStatusBO> timeoutStatusBOMap = listTimeoutMap(Lists.newArrayList(workIdSet));

        // 标准收费单
        Map<Long, ZsWarningVO> warningMap = Maps.newHashMapWithExpectedSize(esOrderWorks.size());
        for (EsOrderWork esOrderWork : esOrderWorks) {
            ZsWarningVO zsWarningVO = new ZsWarningVO();

            // 测试单
            zsWarningVO.setIsTest(esOrderWork.getIsTest());

            // 未完成进行中显示重点渠道
            boolean channelA = Objects.equals(esOrderWork.getResultStatus(), OrderStatusConsts.WORK_RESULT_DOING);
            boolean channelB = esOrderWork.getStatus() < OrderStatusConsts.ORDER_STATUS_COMPLETE;
            if (channelA && channelB && channelMap != null && channelMap.containsKey(esOrderWork.getChannelId())) {
                Integer type = channelMap.get(esOrderWork.getChannelId());
                zsWarningVO.setIsEmphasisChannel(Objects.equals(type, 3));
            }

            // 投诉异常
            if (complainMap != null && complainMap.containsKey(esOrderWork.getId())) {
                TrackAbnormalWarningVO complainLevelDRO = complainMap.get(esOrderWork.getId());
                if (complainLevelDRO != null) {
                    zsWarningVO.setComplainLevel(complainLevelDRO.getLevel());
                    zsWarningVO.setHasAbnormal(complainLevelDRO.getAbnormalStatus());
                    zsWarningVO.setComplainLevelName(complainLevelDRO.getLevelName());
                }
            }

            // 用户vip (要客标识)
//            if (userVipMap != null && userVipMap.containsKey(esOrderWork.getUserId())) {
            zsWarningVO.setIsVip(Objects.equals(esOrderWork.getVvip(), GlobalConsts.YES));
//            }

            // 服务完成待审核
            if (Objects.equals(esOrderWork.getServiceCompleteReviewStatus(), OrderConsts.REVIEW_STATUS_DOING)) {
                zsWarningVO.setIsServiceReview(true);
            }

            // 预警超时
            if (timeoutStatusBOMap != null && timeoutStatusBOMap.containsKey(esOrderWork.getId())) {
                TimeoutStatusBO timeoutStatusBO = timeoutStatusBOMap.get(esOrderWork.getOrderId());
                if (timeoutStatusBO != null) {
                    zsWarningVO.setHasTimeout(timeoutStatusBO.getHasTimeout());
                    zsWarningVO.setHasWarning(timeoutStatusBO.getHasWarning());
                }
            }

            // 一口价 & 进行中
            boolean isFinalPrice = esOrderWork.getIsFinalPrice() && Objects.equals(esOrderWork.getServItemType(), OrderConsts.SERVICE_ITEM_TYPE_QUOTATION_THREE);
            if (isFinalPrice && channelA) {
                zsWarningVO.setIsFinalPrice(true);
            }

            // 增值工单
            if (Objects.equals(esOrderWork.getSourceType(), OrderConsts.ORDER_SOURCE_TYPE_MEMBER)) {
                zsWarningVO.setIsVas(true);
            }

            //  计价器工单预警 (计价器工单、并且状态结果是：未完成-进行中)
            if (Objects.equals(OrderConsts.SERVICE_ITEM_TYPE_FAULT, esOrderWork.getServItemType()) && channelA
                    && channelB) {
                zsWarningVO.setIsQuotation(true);
            }
            //  提前付工单预警
            if (Objects.equals(OrderConsts.SERVICE_ITEM_TYPE_ADVANCE_PAY, esOrderWork.getServItemType()) && channelA
                    && channelB) {
                zsWarningVO.setIsAdvancePay(true);
            }
            //  计价器3.0工单预警
            if (servItemBService.isQuotationThreeType(esOrderWork.getServItemType(), esOrderWork.getIsFinalPrice() ? GlobalConsts.YES : GlobalConsts.NO) && channelA
                    && channelB) {
                zsWarningVO.setIsQuotationThree(true);
            }

            // 挂起订单预警(当工单有挂起原因，并且无：预约时间，并且未完成&未取消，则显示警示)
            List<Integer> supportResultStatusList = Lists.newArrayList(OrderStatusConsts.WORK_RESULT_DOING);
            List<Integer> supportStatus = Lists.newArrayList(
                    OrderStatusConsts.WORK_STATUS_INPUT,
                    OrderStatusConsts.WORK_STATUS_CONFIRM,
                    OrderStatusConsts.WORK_STATUS_ASSIGN,
                    OrderStatusConsts.WORK_STATUS_DISTRIBUTE,
                    OrderStatusConsts.WORK_STATUS_TAKE,
                    OrderStatusConsts.WORK_STATUS_VISIT);
            boolean resultstatus = supportStatus.contains(esOrderWork.getStatus());
            boolean resultStatusSupport = supportResultStatusList.contains(esOrderWork.getResultStatus());
            boolean support = resultstatus && resultStatusSupport;
            boolean status = esOrderWork.getDutyTime() == null && support;
            if (status && Objects.equals(esOrderWork.getDutyStatus(), OrderDutyConsts.DUTY_STATUS_SUSPEND)) {
                zsWarningVO.setIsSuspend(true);
            }
            warningMap.put(esOrderWork.getId(), zsWarningVO);

            List<EsOrderWorkReview> orderWorkReviewList = esOrderWork.getWorkReviewList();
            if (Objects.equals(esOrderWork.getType(), OrderConsts.ORDER_TYPE_REFUND) && CollectionUtils.isNotEmpty(orderWorkReviewList)) {
                // 退款审核标识
                EsOrderWorkReview esOrderWorkReview = orderWorkReviewList.stream().filter(item -> Objects.equals(OrderConsts.OMS_ORDER_REVIEW_REFUND, item.getReviewType())).findAny().orElse(null);
                zsWarningVO.setIsRefundWaitReview(Objects.nonNull(esOrderWorkReview) && Objects.equals(esOrderWorkReview.getReviewStatus(), OrderConsts.OMS_ORDER_REVIEW_STATUS_CHECK));

                // 打款标识
                if (Objects.isNull(esOrderWorkReview)) {
                    zsWarningVO.setIsRemit(Objects.equals(esOrderWork.getPayStatus(), PayConsts.REFUND_STATUS_ING));
                } else {
                    zsWarningVO.setIsRemit(!Objects.equals(esOrderWorkReview.getReviewStatus(), OrderConsts.OMS_ORDER_REVIEW_STATUS_CHECK) && Objects.equals(esOrderWork.getPayStatus(), PayConsts.REFUND_STATUS_ING));
                }
            }

            // 标记
            List<EsOrderTag> esOrderTagList = esOrderWork.getOrderTagList();
            if (CollectionUtil.isNotNullOrEmpty(esOrderTagList)) {
                List<OrderTagVO> tagVOList = esOrderTagList.stream()
                        .filter(item -> confOrderTagMap.containsKey(item.getTagId()))
                        .map(orderTag -> {
                            if (Objects.equals(orderTag.getTagId(), OrderTagConsts.USER_TAG_ID_HIGH_VALUE)) {
                                orderTag.setTagId(OrderTagConsts.TAG_ID_HIGH_VALUE_USER);
                            }
                            ConfOrderTag confOrderTag = confOrderTagMap.get(orderTag.getTagId());
                            return OrderTagVO.builder()
                                    .tagId(orderTag.getTagId())
                                    .tagName(confOrderTag.getTagName())
                                    .tagShortName(confOrderTag.getTagShortName())
                                    .bgColor(confOrderTag.getColor())
                                    .display(confOrderTag.getDisplay()).build();
                        }).collect(Collectors.toList());
                zsWarningVO.setTagList(tagVOList);
            }
        }

        return warningMap;
    }

    @Override
    public List<ZsOrderWorkServiceItemExportVO> converterOrderWorkServiceItemExportVO(List<EsOrderWork> orderWorkList) {

        List<ZsOrderWorkServiceItemExportVO> list = Lists.newArrayList();
        if (CollectionUtils.isEmpty(orderWorkList)) {
            return list;
        }

        for (EsOrderWork esOrderWork : orderWorkList) {
            List<EsOrderWorkServiceItem> serviceItemList = esOrderWork.getServiceItemList();
            if (CollectionUtils.isEmpty(serviceItemList)) {
                ZsOrderWorkServiceItemExportVO vo = getOrderWorkServiceItemVO(esOrderWork);
                list.add(vo);
            } else {
                for (EsOrderWorkServiceItem esOrderWorkServiceItem : serviceItemList) {
                    ZsOrderWorkServiceItemExportVO vo = getOrderWorkServiceItemVO(esOrderWork);
                    vo.setServiceItemName(esOrderWorkServiceItem.getServiceItemName());
                    vo.setServiceItemNum(esOrderWorkServiceItem.getCount());
                    vo.setServiceItemPrice(esOrderWorkServiceItem.getPrice());
                    list.add(vo);
                }
            }
        }
        return list;
    }

    /**
     * 详情默认隐藏用户信息 根据权限显示
     * @param detailVO
     */
    @Override
    public void processUserInfoPermiss(ZsOrderWorkDetailVO detailVO, Integer moduleId) {
        ZsOrderWorkDetailContactVO contactVO = detailVO.getContactVO();
        List<ZsOrderWorkDetailMasterVO> masterVOList = detailVO.getMasterVOList();
        ZsOrderWorkDetailUserInfoVO userInfoVO = detailVO.getUserInfoVO();

        // 用户信息
        if (Objects.nonNull(userInfoVO)) {
            // 加密号码
            userInfoVO.setCryptoMobile(orderEncryptService.encrypt(userInfoVO.getMobile()));
            userInfoVO.setHidMobile(MobileUtil.formatHideTel(userInfoVO.getMobile()));
        }

        // 联系信息
        if (Objects.nonNull(contactVO)) {
            List<String> telList = contactVO.getTelephoneList();
            List<String> telephoneList = Lists.newArrayListWithCapacity(telList.size());
            List<String> hidTelephoneList = Lists.newArrayListWithCapacity(telList.size());
            List<String> telephoneExtensionList = Lists.newArrayListWithCapacity(telList.size());

            for (String telephone : telList) {
                // 判断号码是否有分机号
                String[] split = telephone.split("-");
                if (split.length == 2 && StringUtil.isMobile(split[0])) {
                    telephoneList.add(split[0]);
                    telephoneExtensionList.add(split[1]);
                    hidTelephoneList.add(MobileUtil.formatHideTel(split[0]));
                } else {
                    telephoneList.add(telephone);
                    telephoneExtensionList.add("");
                    hidTelephoneList.add(MobileUtil.formatHideTel(telephone));
                }
            }

            contactVO.setTelephoneList(telephoneList);
            contactVO.setTelephoneExtensionList(telephoneExtensionList);
            contactVO.setHidTelephoneList(hidTelephoneList);

            // 加密号码
            contactVO.setCryptoTelephoneList(orderEncryptService.encrypt(telephoneList));

            // 地址
            contactVO.setStreet("*****");
            contactVO.setAddress("*****");
            contactVO.setFullAddress(String.join(" ", contactVO.getProvinceName(), contactVO.getCityName(), contactVO.getCountyName(), "*****"));
        }

        // 工程师号码
        if (Objects.nonNull(masterVOList)) {
            for (ZsOrderWorkDetailMasterVO zsOrderWorkDetailMasterVO : masterVOList) {
                zsOrderWorkDetailMasterVO.setCryptoMasterPhone(orderEncryptService.encrypt(zsOrderWorkDetailMasterVO.getMasterPhone()));
                zsOrderWorkDetailMasterVO.setHideMasterPhone(MobileUtil.formatHideTel((zsOrderWorkDetailMasterVO.getMasterPhone())));
            }
        }

        // 新增日志手机号脱敏处理
        String detailPermitUrl = OrderPremissionConsts.getDetailPermitUrl(moduleId, OrderPremissionConsts.ODP_VIEW_ALL_LOG);
        boolean permitted = StaffAdminService.isPermitted(detailPermitUrl);
        Optional<OrderLog> orderLogOptional = detailVO.getLogList().stream().filter(e -> Objects.equals(e.getType(), OrderLogConsts.ORDER_LOG_TYPE_INPUT)).findAny();
        if (!permitted && orderLogOptional.isPresent()) {
            String content = orderLogOptional.get().getContent();
            orderLogOptional.get().setContent(MobileUtil.formatTextHideTel(content));
        }
    }

    private ZsOrderWorkServiceItemExportVO getOrderWorkServiceItemVO(EsOrderWork esOrderWork) {
        ZsOrderWorkServiceItemExportVO vo = BeanMapper.map(esOrderWork, ZsOrderWorkServiceItemExportVO.class);
        List<EsOrderWorkProduct> productList = esOrderWork.getProductList();
        if (!CollectionUtils.isEmpty(productList)) {
            vo.setProductName(productList.get(0).getProductName());
            vo.setProductNum(productList.get(0).getNumber());
        }
        return vo;
    }

    @Override
    public List<EsOrderWork> exportListOrderWorkByQuery(OrderWorkQuery query) {
        return orderWorkListBService.listPageOrderWorkByQuery(query);
    }

    /**
     * 查询重点渠道
     * @param channelIdList
     * @return
     */
    private Map<Integer, Integer> listChannelPlatformTypeMap(List<Integer> channelIdList) {
        Map<Integer, Integer> channelMap = null;
        ResponseDTO<List<ChannelDRO>> channelResponseDTO = channelListRemoteService
                .listByChannelIds(channelIdList);
        if (channelResponseDTO.isSuccess() && !CollectionUtils.isEmpty(channelResponseDTO.getData())) {
            channelMap = channelResponseDTO.getData().stream().filter(e -> Objects.nonNull(e.getLevel()))
                    .collect(Collectors.toMap(ChannelDRO::getChannelId, ChannelDRO::getLevel));
        }
        return channelMap;
    }

    /**
     * 查询投诉异常警告
     * @param workIdList
     * @return
     */
    private Map<Long, TrackAbnormalWarningVO> listTrackComplainMap(List<Long> workIdList) {
        if (CollectionUtil.isNullOrEmpty(workIdList)) {
            return null;
        }
        Map<Long, TrackAbnormalWarningVO> trackComplainVOMap = Maps.newHashMap();

        // 异常
        try {
            ResponseDTO<List<AbnorAbnormalOrderDRO>> abnormalResponse = abnormalListRemoteService.listHasAbnormalByOrderIdList(workIdList);
            if (CollectionUtil.isNotNullOrEmpty(abnormalResponse.getData())) {
                abnormalResponse.getData().forEach(e -> {
                    trackComplainVOMap.put(e.getOrderId(),
                            TrackAbnormalWarningVO.builder()
                                    .orderId(e.getOrderId())
                                    .abnormalStatus(e.getExistAbnormal())
                                    .level(0)
                                    .levelName("")
                                    .build());
                });
            }
        } catch (Exception ex) {
        }
        // 投诉
        try {
            ResponseDTO<List<ChsComplainLevelDRO>> trackResponse = chsComplainApiListRemoteService.listComplainLevelByOrderIdList(workIdList);
            if (CollectionUtil.isNotNullOrEmpty(trackResponse.getData())) {
                trackResponse.getData().forEach(e -> {
                    if (trackComplainVOMap.containsKey(e.getOrderId())) {
                        TrackAbnormalWarningVO obj = trackComplainVOMap.get(e.getOrderId());
                        obj.setLevel(e.getLevel());
                        obj.setLevelName(e.getLevelName());
                    } else {
                        trackComplainVOMap.put(e.getOrderId(),
                                TrackAbnormalWarningVO.builder()
                                        .orderId(e.getOrderId())
                                        .abnormalStatus(false)
                                        .level(e.getLevel())
                                        .levelName(e.getLevelName())
                                        .build());
                    }

                });
            }
        } catch (Exception ex) {
        }
        return trackComplainVOMap;
    }

    /**
     * 查询工单预警超时
     * @param workIdList
     * @return
     */
    @SneakyThrows
    private Map<Long, TimeoutStatusBO> listTimeoutMap(List<Long> workIdList) {
        try {
            com.zmn.common.dto2.ResponseDTO<Set<OrderTimeOutWarningCheckDRO>> responseDTO = orderTimeoutWarningListService
                    .checkOrderTimeoutWarning(Sets.newHashSet(workIdList));
            if (!responseDTO.isSuccess()) {
                throw new OmsBaseException(
                        String.format("orderTimeoutWarningListService.checkOrderTimeoutWarning(%s),调用出错", workIdList));
            }
            Set<OrderTimeOutWarningCheckDRO> orderTimeOutWarningCheckDROS = Optional.ofNullable(responseDTO.getData())
                    .orElse(Collections.emptySet());

            Map<Long, TimeoutStatusBO> complainMap = orderTimeOutWarningCheckDROS.stream()
                    .collect(Collectors.toMap(OrderTimeOutWarningCheckDRO::getOrderId, orderTimeOutWarningCheckDRO -> {
                        TimeoutStatusBO timeoutStatusBO = new TimeoutStatusBO();
                        timeoutStatusBO.setWorkId(orderTimeOutWarningCheckDRO.getOrderId());
                        timeoutStatusBO.setHasWarning(orderTimeOutWarningCheckDRO.getHasWarning());
                        timeoutStatusBO.setHasTimeout(orderTimeOutWarningCheckDRO.getHasTimeout());
                        return timeoutStatusBO;
                    }));
        } catch (Exception ex) {
            logger.error("查询预警失败：", ex);
        }

        return Maps.newHashMap();
    }

    /**
     * 查询渠道预警
     * @param
     * @return
     */
    private boolean listChannelWarningMap(Long workId, OrderTmallExtend orderTmallExtend) {
        boolean isSingIn = false;
        boolean isWarning = false;
        // 是否签到
        if (Objects.nonNull(orderTmallExtend)) {
            //签到失败并且未核销触发预警
            if (Objects.equals(orderTmallExtend.getSignInStatus(), GlobalConsts.NO) && Objects
                    .isNull(orderTmallExtend.getVerificationTime())) {
                isSingIn = true;
            }
        }

        // 是否有延期预警
        OrderWarnQuery orderWarnQuery = new OrderWarnQuery();
        orderWarnQuery.setOrderId(workId);
        orderWarnQuery.setBizStatus(GlobalConsts.NO);
        List<OrderWarn> list = orderWarnService.listOrderWarns(orderWarnQuery);
        isWarning = list.size() != 0;

        return isSingIn || isWarning;
    }

    /**
     * 查询工程师早上门预警
     * @param
     * @return
     */
    private boolean listVisitEarlyWarningMap(OrderTmallExtend orderTmallExtend) {
        boolean isVisitEarly = false;
        // 是否签到
        if (Objects.nonNull(orderTmallExtend)) {
            //签到失败并且未核销触发预警
            if (Objects.equals(orderTmallExtend.getVisitEarlyFlag(), GlobalConsts.YES)) {
                isVisitEarly = true;
            }
        }
        return isVisitEarly;
    }

    /**
     * 获取工程师在线状态dro集合
     * @param masterIdList
     * @return
     */
    private Map<Integer, ForeignEngineerOnlineStatusDRO> listMasterOnlineStatusDROMap(OrderWork orderWork,
                                                                               Set<Integer> masterIdList) {
        //已派单-已领单-已上门”&“进行中”工单，在主工程师/多工程师右侧拼上“在线/离线”的字样
        Integer resultStatus = orderWork.getResultStatus();
        List statusList = Lists
                .newArrayList(OrderStatusConsts.WORK_STATUS_DISTRIBUTE, OrderStatusConsts.WORK_STATUS_TAKE,
                        OrderStatusConsts.WORK_STATUS_VISIT);

        if (statusList.contains(orderWork.getStatus()) && Objects
                .equals(OrderStatusConsts.WORK_RESULT_DOING, resultStatus)) {
            try {

                //com.zmn.common.dto2.ResponseDTO<List<EngineerOnlineStatusDRO>> responseDTO = engineerTouchListRemoteService
                //      .listEngineerOnlineStatusByEngineerIds(masterIdList);
//                Set<Integer> masterIdSet = new HashSet<>(masterIdList);
                logger.debug("listMasterOnlineStatusDROMap#listEngineerOnlineStatusByIdSet 入参 [{}]", JSON.toJSONString(masterIdList));
                ResponseDTO<List<ForeignEngineerOnlineStatusDRO>> responseDTO = engineerOnlineRemoteService.listEngineerOnlineStatusByIdSet(masterIdList);
                logger.debug("listMasterOnlineStatusDROMap#listEngineerOnlineStatusByIdSet 出参 [{}]", JSON.toJSONString(responseDTO));
                //logger.info("获取工程师在线状态dro集合出参[{}]", responseDTO);
                if (!responseDTO.isSuccess() || CollectionUtils.isEmpty(responseDTO.getData())) {
                    return Maps.newHashMap();
                }

                Map<Integer, ForeignEngineerOnlineStatusDRO> collect = responseDTO.getData().stream()
                        .collect(Collectors.toMap(ForeignEngineerOnlineStatusDRO::getEngineerId, e -> e));

                return collect;
            } catch (Exception ex) {
            }
        }

        return Maps.newHashMap();
    }

    private void processChannelDescription(OrderWork orderWork, ZsOrderWorkDetailVO detailVO, Integer fcOrderId) {
        String channelDescription = "暂无";
        //厂商单
        if (Objects.equals(OrderConsts.ORDER_SOURCE_TYPE_FACTORY, orderWork.getSourceType()) && NumberUtil
                .isNotNullOrZero(fcOrderId)) {
            /*ResponseDTO<String> factoryDescDTO = factoryListRemoteService.getFactoryServiceDesc(fcOrderId);
            if (!factoryDescDTO.isSuccess()) {
                logger.error("获取厂商服务说明异常[{}]", factoryDescDTO.getMessage());
                detailVO.setChannelDescription("暂无");
                return;
            } else {
                channelDescription = StringUtils.isBlank(factoryDescDTO.getData()) ? "暂无" : factoryDescDTO.getData();
            }*/

        } else {
            try {
                ConfOrderChannelDRO confOrderChannelDRO = confOrderChannelBService.getByChannelId(orderWork.getChannelId());
                if (Objects.isNull(confOrderChannelDRO)) {
                    logger.error("#oms#orderdetail#渠道不存在{} ", orderWork.getWorkId());
                    detailVO.setChannelDescription("暂无");
                    return;
                }

                channelDescription = StringUtils.isBlank(confOrderChannelDRO.getScale()) ? "暂无" : confOrderChannelDRO.getScale();
                if (Objects.equals(confOrderChannelDRO.getInviteComment(), GlobalConsts.YES)) {
                    detailVO.setInviteCommentPlat(StringUtils.defaultString(confOrderChannelDRO.getInviteCommentPlat(), "暂无"));
                    detailVO.setInviteCommentExplain(StringUtils.defaultString(confOrderChannelDRO.getInviteCommentExplain(), "暂无"));
                }
                if (Objects.equals(confOrderChannelDRO.getGuideThirdPartPay(), GlobalConsts.YES)) {
                    detailVO.setFinalPaymentPayPlat(StringUtils.defaultString(confOrderChannelDRO.getPayPlat(), "暂无"));
                    detailVO.setFinalPayExplain(StringUtils.defaultString(confOrderChannelDRO.getPayExplain(), "暂无"));
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }

        detailVO.setChannelDescription(channelDescription);
    }

    /**
     * 处理结算价格  产品需求 2020.11.30
     * 工单详情必须展示 销售价、内部价、外部价，即使无默认服务项，则查询默认服务项价格也进行显示
     *
     * @param orderWork
     * @param detailVO
     */
    private void processSettlementPrice(OrderWork orderWork, ZsOrderWorkDetailVO detailVO, List<OrderProduct> orderProductList) {
        // 存在服务项目则不处理
        if (CollectionUtil.isNotNullOrEmpty(detailVO.getServiceItemList())) {
            return;
        }

        // 不是进行中
        if (!Objects.equals(OrderStatusConsts.WORK_RESULT_DOING, orderWork.getResultStatus())) {
            return;
        }

        // 不是新单
        if (!Objects.equals(OrderConsts.ORDER_TYPE_NEW, orderWork.getType())) {
            return;
        }

        // 无产品信息
        if (CollectionUtil.isNullOrEmpty(orderProductList)) {
            return;
        }

        OrderProduct orderProduct = orderProductList.get(0);
        if (Objects.isNull(orderProduct)) {
            return;
        }
        // 前台产品没有对应后台产品
        if (NumberUtil.isNullOrZero(orderWork.getProductId())) {
            logger.info("#order#serviceitem orderId:{} 前台产品没有找到对应的后台产品。 前台产品ID：{}", orderWork.getOrderId(), orderWork.getShowProductId());
            return;
        }
        // 查询默认故障服务项
        Integer brandId = NumberUtil.isNotNullOrZero(orderProduct.getBrandId()) ? orderProduct.getBrandId() : 1051;// 为空取其他品牌
        OrderServItemTypeDTO orderServItemTypeDTO = new OrderServItemTypeDTO();
        orderServItemTypeDTO.setChannelId(orderWork.getChannelId());
        orderServItemTypeDTO.setCityId(orderWork.getCityId());
        orderServItemTypeDTO.setProductId(orderWork.getProductId());
        orderServItemTypeDTO.setBrandId(brandId);
        orderServItemTypeDTO.setBizType(orderWork.getBizType());

        if (Objects.equals(orderWork.getFinalPrice(), GlobalConsts.YES)) {
            MeterItemPriceQuery build = MeterItemPriceQuery
                    .builder()
                    .bizType(orderWork.getBizType())
                    .brandId(brandId)
                    .channelId(orderWork.getChannelId())
                    .cityId(orderWork.getCityId())
                    .productId(orderWork.getProductId())
                    .itemStandard(GlobalConsts.YES)
                    .build();
            logger.info("#order#price orderId={}, 一口价类型默认故障项入参 :{}", orderWork.getOrderId(), JSON.toJSONString(build));
            ResponseDTO<List<ItemDRO>> responseDTO = null;
            try {
                responseDTO = meterFlow2RemoteService.listItemPriceByPriceStandard(build);
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }
            logger.info("#order#price orderId={}, 一口价类型默认故障项出参 :{}", orderWork.getOrderId(), JSON.toJSONString(responseDTO));
            if (!responseDTO.isSuccess() || CollectionUtils.isEmpty(responseDTO.getData())) {
                return;
            }
            // 无默认服务项
            Optional<ItemDRO> defaultItemOptional = responseDTO.getData().stream()
                    .filter(e -> !Objects.isNull(e.getPrice()))
                    .findFirst();

            if (!defaultItemOptional.isPresent()) {
                logger.error("#order#serviceitem 产品无默认服务项  orderId:{} 出参：{}", orderWork.getOrderId(), JSON.toJSONString(responseDTO.getData()));
                return;
            }
            ItemDRO defaultFaultItemDRO = defaultItemOptional.get();
            detailVO.setOriginalAmount(defaultFaultItemDRO.getPrice());
            detailVO.setInternalSettlementAmount(defaultFaultItemDRO.getPriceInternalSettlement());
            detailVO.setExternalSettlementAmount(defaultFaultItemDRO.getPriceExternalSettlement());

        } else {
            ItemPriceQuery itemPriceQuery = ItemPriceQuery
                    .builder()
                    .productId(orderServItemTypeDTO.getProductId())
                    .showType(BaseProductConsts.ERP_SHOW_TYPE)
                    .bizType(orderServItemTypeDTO.getBizType())
                    .cityId(orderServItemTypeDTO.getCityId())
                    .channelId(orderServItemTypeDTO.getChannelId())
                    .brandId(orderServItemTypeDTO.getBrandId())
                    .build();
            ResponseDTO<List<ItemDRO>> itemResponseDTO = null;
            try {
                itemResponseDTO = itemPriceRemoteService.listItemPriceByQuery(itemPriceQuery);
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }
            List<ItemDRO> itemDROS = itemResponseDTO.getData();
            if (CollectionUtils.isEmpty(itemDROS)) {
                return;
            }
            // 查询默认服务项
            ItemDRO defaultItemDRO = itemDROS.stream().filter(item -> Objects.equals(GlobalConsts.YES, item.getDefaultSkuPrice())).findAny().orElse(null);
            if (defaultItemDRO == null) {
                return;
            }
            detailVO.setOriginalAmount(defaultItemDRO.getPrice());
            detailVO.setInternalSettlementAmount(defaultItemDRO.getPriceInternalSettlement());
            detailVO.setExternalSettlementAmount(defaultItemDRO.getPriceExternalSettlement());
        }
    }


    /**
     * 处理临时小号
     *
     * @param orderWork
     */
    private void processTempXnoBind(OrderWork orderWork, ZsOrderWorkDetailContactVO contactVO) {
        OrderXnoBindQuery xnoBindQuery = OrderXnoBindQuery.builder()
                .workIdList(Lists.newArrayList(orderWork.getWorkId()))
                .bindType(OrderXnoConsts.BIND_TYPE_TEMP)
                .bindStatus(OrderConsts.BIND_STATUS_BIND)
                .build();
        List<OrderXnoBind> orderXnoBindList = orderXnoService.queryOrderXnoBindListByQuery(xnoBindQuery);
        if (CollectionUtil.isNullOrEmpty(orderXnoBindList)) {
            return;
        }
        List<String> tempXnoList = Lists.newArrayListWithCapacity(orderXnoBindList.size());
        List<String> tempXnoOperatorList = Lists.newArrayListWithCapacity(orderXnoBindList.size());
        orderXnoBindList.forEach(orderXnoBind -> {
            tempXnoList.add(orderXnoBind.getXnoTelephone());
            tempXnoOperatorList.add(orderXnoBind.getCreater());
        });
        contactVO.setTempXnoList(tempXnoList);
        contactVO.setTempXnoOperatorList(tempXnoOperatorList);
    }

    /**
     *
     * @param orderId
     * @param workId
     */
    private void isExistTrack(Long orderId, Long workId,ZsOrderWorkDetailVO detailVO){
        logger.info("orderId={},workId={}", orderId, workId);

        detailVO.setExistTrack(false);

        TrackWorkQuery query = new TrackWorkQuery();
        query.setOrderId(orderId);
        query.setWorkId(workId);
        try {
            ResponseDTO<List<TrackWorkDRO>> listResponseDTO = trackWorkListRemoteService.listTrackByQuery(query);
            if (listResponseDTO.isSuccess()) {
                List<TrackWorkDRO> trackWorkDROList = listResponseDTO.getData();
                detailVO.setExistTrack(CollectionUtil.isNotNullOrEmpty(trackWorkDROList));

                boolean existOngoingTrack = trackWorkDROList.stream()
                        .anyMatch(e -> !Objects.equals(e.getStatus(), TrackConsts.TRACK_STATUS_FINISHED));
                detailVO.setExistOngoingTrack(existOngoingTrack);
            }
        } catch (Exception e) {
            logger.error("com.zmn.oms.zmn.business.impl.work.ZsOrderWorkQueryBServiceImpl.isExistTrack error={}", e.getMessage());
        }
    }

    private void processTimesCardRefundAmount(ZsOrderWorkDetailVO detail)  {
        // 如果是次卡
        if (NumberUtil.isNotNullOrZero(detail.getDiscountPrepayAmount())) {
            List<ZsOrderWorkDetailDiscountVO> discountList = detail.getDiscountVOList();
            if (CollectionUtils.isEmpty(discountList)) {
                return;
            }
            Optional<ZsOrderWorkDetailDiscountVO> discountOptional = discountList.stream().filter(e -> Objects.equals(e.getCateg(), DiscountTypeEnums.DISCOUNT_COUP_ONCECARD.getSubType())).findFirst();
            if (discountOptional.isPresent()) {
                ResponseDTO<OrderTimesCardDRO> coupResponseDTO = null;
                try {
                    coupResponseDTO = vasOrderTimesCardListRemoteService.getOrderTimesCardByCouponCode(discountOptional.get().getCouponCode());
                } catch (Exception e) {
                    e.printStackTrace();
                    return;
                }
                logger.debug("退款查询次卡信息 入参：{} 出参：{}", discountOptional.get().getCouponCode(), JSON.toJSONString(coupResponseDTO));
                if (coupResponseDTO.isSuccess()) {
                    OrderTimesCardDRO dro = coupResponseDTO.getData();
                    detail.setDiscountPrepayRefundAmount(dro.getRefundAmount());
                }
            }

        }
    }

    /**
     * 渠道代收金额明细
     *
     * @param orderWork
     * @return
     */
    private String processChannelPrepayList(OrderWork orderWork) {
        List<OrderChannelPrepay> channelPrepayList = orderChannelPrepayService.listOrderChannelPrepayByOrderIdAndWorkId(orderWork.getOrderId(), orderWork.getWorkId());
        if (CollectionUtil.isNotNullOrEmpty(channelPrepayList)) {
            Integer sum = channelPrepayList.stream().mapToInt(OrderChannelPrepay::getAmount).sum();
            StringJoiner sj = new StringJoiner("，");
            sj.add("（实收金额：" + MoneyUtil.parseToYuanStartWithUnit(orderWork.getChannelPrepayAmount() - sum));
            channelPrepayList.forEach(e -> {
                sj.add(e.getPrepayTypeName() + "：" + MoneyUtil.parseToYuanStartWithUnit(e.getAmount()));
            });
            return sj.toString() + "）";
        } else if (NumberUtil.isNotNullOrZero(orderWork.getChannelPrepayAmount())) {
            return "（实收金额：" + MoneyUtil.parseToYuanStartWithUnit(orderWork.getChannelPrepayAmount()) + "）";
        }
        return "";
    }
    private void getOrderPayDiscountList(ZsOrderWorkDetailVO detailVO) {
        if (Objects.isNull(detailVO) || Objects.isNull(detailVO.getOrderId())) {
            return;
        }
        final List<OrderPayDiscount> orderPayDiscountList = orderPayDiscountService.listOrderPayDiscountByOrderId(detailVO.getOrderId());
        detailVO.setOrderPayDiscountList(orderPayDiscountList);
    }

    /**
     * 获取工程师列表信息
     * @param masterIds
     * @param bizType
     * @return
     */
    private Map<Integer, ForeignEngineerDetailInfoDRO> getEngineerBasicDetailInfoMap(Set<Integer> masterIds, Integer bizType) {
        if (CollectionUtil.isNullOrEmpty(masterIds)) {
            return Collections.emptyMap();
        }
        try {
            ForeignEngineerQuery query = new ForeignEngineerQuery();
            query.setEngineerIdSet(masterIds);
            query.setBizType(bizType);
            // 设置查询工程师合作对象信息
            query.setLoadCooperate(Boolean.TRUE);
            query.setPageSize(masterIds.size());
            ResponseDTO<IPageInfo<ForeignEngineerDetailInfoDRO>> responseDTO = engineerListRemoteService.listEngineerPageByQuery(query);
            if (logger.isDebugEnabled()) {
                logger.debug("#getEngineerBasicDetailInfoMap#listEngineerPageByQuery-入参:{}-出参:{}", query, responseDTO);
            }
            if (!responseDTO.isSuccess() || Objects.isNull(responseDTO.getData()) || CollectionUtil.isNullOrEmpty(responseDTO.getData().getRecords())) {
                logger.warn("getEngineerBasicDetailInfoMap 获取工程师 信息数据失败 masterIds:{}", masterIds);
                return Collections.emptyMap();
            }

            return  responseDTO.getData().getRecords().stream().collect(Collectors.toMap(ForeignEngineerDetailInfoDRO::getEngineerId, Function.identity()));

        } catch (Exception e) {
            logger.error("getEngineerBasicDetailInfoMap 获取工程师 信息数据异常 masterIds:{},e:{}", masterIds, e);
            return Collections.emptyMap();
        }
    }

}
